1. Add the Signalr service:
services.AddSignalR();
2. Create a hub:
public class MyHub: Hub {
public override Task OnConnectedAsync() {
/* Save somewhere the connection id based on authentication */
}
public override Task OnDisconnectedAsync() {
/* ... */
}
}
Keep in mind that the hub instance is created per connection. Whenever a client reconnects a new hub instance is created. That is the reason why it is better to keep separately a map of the user -> connection id.
3. Add the middleware as an endpoint option:
app.UseEndpoints(endpoints =>
{
/* Other endpoints */
endpoints.MapHub<MyHub>("/myhub");
});
This part automatically registers the /signalr endpoint.
4. An example for .NET client:
var connection = new HubConnectionBuilder()
.WithUrl("https://localhost:44354/myhub")
.WithAutomaticReconnect()
.Build();
try {
connection.StartAsync().Wait();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}