My signalR hub works good. I configure it with simple example.
StartUp.cs
services.AddSignalR();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<BroadcastHub>("/notify");
});
Interface IHubClient
public interface IHubClient
{
Task BroadcastMessage();
Task BroadcastToConnection(string data, string connectionId);
Task BroadcastToUser(string data);
}
BroadcastHub.cs
public class BroadcastHub : Hub<IHubClient>
{
public ClaimsPrincipal GetConnectionId() => Context.ConnectionId;
}
My angular side
ngOnInit(): void {
this.connection = new signalR.HubConnectionBuilder()
.configureLogging(signalR.LogLevel.Information)
.withUrl(`${environment.apiUrl}/` + 'notify')
.build();
this.connection
.start()
.then(function () {
})
.then(() => this.getConnectionId())
.catch(function (err) {
return console.error(err.toString());
});
this.connection.on("BroadcastToUser", (e) => {
console.log(e);
});
}
getConnectionId = () => {
this.connection.invoke('getconnectionid').then(
(data) => {
console.log(data);
this.connectionId = data;
}
);
}
I can easy send message by connectionId through swagger by this way and it works good
[HttpGet("signalr/{id}")]
public async Task<string> Signalr(string id)
{
await _hubContext.Clients.Client(id).BroadcastToUser("test");
return "message send to: " + id;
}
But I want to send by userId and use this method - UserId I get from context
await _hubContext.Clients.User(UserId).BroadcastToUser("test");
But I don't see any result. As I read on code-mase in this example I need to authenticate users and set the NameIdentifier claim in ClaimsPrincipal
I use Auth web api in my .NET app. My atribute [Authorize(Roles = "User")] works good. I dont understand how I can send message by userId