user1476860
user1476860

Reputation: 139

How to use IUserIdProvider in .NET Core?

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?

Upvotes: 8

Views: 8791

Answers (2)

AlbertK
AlbertK

Reputation: 13237

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()

Upvotes: 13

Barr J
Barr J

Reputation: 10927

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.

Upvotes: 1

Related Questions