forked from Ibro/SignalRSimpleChat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChatService.cs
51 lines (41 loc) · 1.61 KB
/
ChatService.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
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.SignalR.Client;
using System.Security.Claims;
namespace SignalRSimpleChat;
public class ChatService( ILogger<ChatService> logger, AuthenticationStateProvider AuthenticationStateProvider) : IAsyncDisposable
{
private HubConnection _connection;
private readonly ILogger _logger = logger;
private readonly AuthenticationStateProvider _authenticationStateProvider = AuthenticationStateProvider;
private ClaimsPrincipal User { get; set; }
public async Task ConnectAsync()
{
var authState = await _authenticationStateProvider.GetAuthenticationStateAsync();
User = authState.User;
_connection = new HubConnectionBuilder()
.WithUrl( $"https://localhost:44393{ChatHub.HubUrl}" )
.Build();
_connection.On<string, string>( ChatHub.SendToAllClient, (user, message) =>
{
OnSendToAllMessage.Invoke( user, message );
} );
if ( _connection.State != HubConnectionState.Connected )
{
await _connection.StartAsync( );
ChatHub.AddUser(_connection.ConnectionId, User.Identity.Name);
}
}
public Action<string, string> OnSendToAllMessage { get; set; }
public async Task SendToAll(string sender, string message)
{
var serverMethodName = nameof( ChatHub.SendToAll );
await _connection.InvokeAsync( serverMethodName, sender, message );
}
public async ValueTask DisposeAsync()
{
if ( _connection != null )
{
await _connection.DisposeAsync( );
}
}
}