I'm trying to send a message to a specific client in my Blazor WebAssembly project.
Startup.cs
services.AddSignalR();
....
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapHub<OrderHub>("/orderhub");
endpoints.MapFallbackToFile("index.html");
});
Client Code
protected override async Task OnInitializedAsync()
{
hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/orderhub"))
.Build();
await hubConnection.StartAsync();
await hubConnection.SendAsync("SendItemsCountMessage", orderpositions.Sum(x => x.amount));
}
Hub.cs
public class OrderHub : Hub
{
public async Task SendItemsCountMessage(int ItemsCount)
{
await Clients.All.SendAsync("ReceiveItemMessage", ItemsCount);
}
}
Now I want to change it to have the option to send to a specific user:
public async Task SendItemsCountMessage(int ItemsCount)
{
string conID = Context.ConnectionId;
await Clients.User(conID).SendAsync("ReceiveItemMessage", ItemsCount);
}
But the context is null, with a user or without, with a logged in user or unauthorized, it all doesn't seems to matter. Any idea how to get the right Context.ConnectionId
, best without being logged in user?
Maybe I need something like this?
Is it possible that I have to use bearer token authentication in my application and then send a generated token to Hub.cs
where with var context = HttpContext.Request.Query[Token]
I can get my Context
?