如何在 .NET Core 中使用 IUserIdProvider?

How to use IUserIdProvider in .NET Core?

This article 描述使用 IUserIdProvider 接口。它显示了如何使用 GlobalHost 使 SignalR 使用您的用户 ID 提供程序。但是 .Net Core 的 SignalR 没有 GlobalHost。什么是替代品?

在 .Net 核心中,您拥有 DI 注入服务 Microsoft.AspNet.SignalR.Infrastructure.IConnectionManager,您可以在其中获取上下文。

例如,要获取您使用的连接管理器:

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

你甚至可以在中间件中获取上下文:

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

您可以阅读更多内容here

您需要实施 IUserIdProvider

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

然后需要在Startup中注册,用于依赖注入:

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

然后 SignalR 将在 HubEndPoint.OnConnectedAsync()

等事件中使用您的 UserIdProvider