7

This article describes using IUserIdProvider interface. It shows how you can use GlobalHost to make SignalR use you user ID provider. But SignalR for .Net Core does not have GlobalHost. What is the replacement?

Boppity Bop
  • 9,613
  • 13
  • 72
  • 151
user1476860
  • 119
  • 2
  • 9

2 Answers2

11

You need to implement IUserIdProvider.

public class MyCustomProvider : IUserIdProvider
{
    public string GetUserId(HubConnectionContext connection)
    {
        ...
    }
}

Then you need to register it in Startup for dependency injection:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();
    services.AddSingleton<IUserIdProvider, MyCustomProvider>();
}

Then SignalR will use your UserIdProvider in such events like HubEndPoint.OnConnectedAsync()

AlbertK
  • 11,841
  • 5
  • 40
  • 36
  • 1
    Thank you very much. services.AddSingleton is what I was looking for. It works – user1476860 Aug 23 '18 at 08:49
  • 1
    Thank you! I was porting an old Hub that explicitly created an instance of `UserIdProvider` and called `GetUserId` with dotnet core you don't have to do this as @AlbertK mentioned `GetUserId` will be called automatically by OnConnectedAsync and you can get its value by calling `Context.UserIdentifier` – Roberto Alarcon Jun 30 '22 at 01:29
1

In .Net core you have the DI injected service Microsoft.AspNet.SignalR.Infrastructure.IConnectionManager where you can get the context.

for example, to get connection manager you use:

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Infrastructure;
using Microsoft.AspNet.Mvc;

public class TestController : Controller
{
     private IHubContext testHub;

     public TestController(IConnectionManager connectionManager)
     {
         //get connection manager using HubContext
         testHub = connectionManager.GetHubContext<TestHub>();
     }
}

You can even get the context in the middleware:

app.Use(next => (context) =>
{
    var hubContext = (IHubContext<MyHub>)context
                        .RequestServices
                        .GetServices<IHubContext<MyHub>>();
    //...
});

You can read more here.

Barr J
  • 10,636
  • 1
  • 28
  • 46