-
Notifications
You must be signed in to change notification settings - Fork 0
/
SignalR.razor.cs
52 lines (45 loc) · 1.72 KB
/
SignalR.razor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Microsoft.AspNetCore.SignalR.Client;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace SignalRAuthTest.Client.Pages
{
public partial class SignalR : ComponentBase
{
[Inject]
IAccessTokenProvider tokenProvider { get; set; }
private HubConnection hubConnection;
private List<string> messages = new List<string>();
private string userInput;
private string messageInput;
protected override async Task OnInitializedAsync()
{
var tokenResult = await tokenProvider.RequestAccessToken();
if (tokenResult.TryGetToken(out var token))
{
hubConnection = new HubConnectionBuilder()
.WithUrl(
NavigationManager.ToAbsoluteUri("/messageshub/?access_token={token.Value}")
)
.Build();
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
var encodedMsg = $"{user}: {message}";
messages.Add(encodedMsg);
StateHasChanged();
});
await hubConnection.StartAsync();
}
}
public Task Send() =>
hubConnection.SendAsync("SendMessage", userInput, messageInput);
public bool IsConnected =>
hubConnection != null ?
hubConnection.State == HubConnectionState.Connected : false;
public void Dispose()
{
_ = hubConnection.DisposeAsync();
}
}
}