I have a web API project which is configured to connect to Azure SignalR and clients can connect to it through its hub.
Web Api:
[Authorize]
public class ClientHub : Hub
{
private string GroupName
{
get
{
return $"{Context?.User?.GetClaim(ClaimTypes.Role) ?? null}_{ Context?.User?.GetClaim(ClaimType.hdid) ?? null}";
}
}
public ClientHub()
{
}
public async override Task OnConnectedAsync()
{
Console.WriteLine("OnConnectedAsync");
await Groups.AddToGroupAsync(Context?.ConnectionId, GroupName);
await base.OnConnectedAsync();
}
public override Task OnDisconnectedAsync(Exception exception)
{
Console.WriteLine("OnDisconnectedAsync");
return base.OnDisconnectedAsync(exception);
}
}
public class SignalRService : IDataPushService
{
private readonly IHubContext<ClientHub> _hubContext;
public SignalRService(IHubContext<ClientHub> hubContext)
{
_hubContext = hubContext;
}
public Task Receive(string data)
{
return Task.FromResult(0);
}
public async Task Send(PushServiceDataPackage dataPackage)
{
await _hubContext.Clients.Group(dataPackage.GroupName)
.SendAsync(dataPackage.EventType.ToString(), dataPackage.Data);
}
}
ConfigureServices method
// Add SignalR service
bool.TryParse(configuration["SignalRSettings:EnableDetailedErrors"], out bool enableDetailedErrors);
services.AddSignalR(config => config.EnableDetailedErrors = enableDetailedErrors).AddAzureSignalR(configuration["SignalRSettings:ConnectionString"]);
Configure method:
endpoints.MapHub<ClientHub>(configuration["SignalRSettings:HubPath"]);
Console App: I also have a console app that is meant to use the same SignalR server to send data to connected clients.
bool.TryParse(hostContext.Configuration["SignalRSettings:EnableDetailedErrors"], out bool enableDetailedErrors);
services.AddSignalR(config => config.EnableDetailedErrors = enableDetailedErrors).AddAzureSignalR(hostContext.Configuration["SignalRSettings:ConnectionString"]);
public class SignalRService : IDataPushService
{
private readonly IHubContext<Hub> _hubContext;
public SignalRService(IHubContext<Hub> hubContext)
{
_hubContext = hubContext;
}
public Task Receive(string data)
{
return Task.FromResult(0);
}
public async Task Send(PushServiceDataPackage dataPackage)
{
await _hubContext.Clients.Group(dataPackage.GroupName)
.SendAsync(dataPackage.EventType.ToString(), dataPackage.Data);
}
}
How can I access the clients connected to the server in the console app?
Please note that there are two apps and one Azure SignalR server?