SignalR IUserIdProvider未为用户ID和连接ID映射调用
本文关键字:ID 连接 映射 调用 用户 IUserIdProvider SignalR | 更新日期: 2023-09-27 18:24:56
当我向信号员发出请求时,我正在从javascript发送userid,如下所示:
var userId = "1";
var connection = $.hubConnection("/signalr", { useDefaultPath: false });
var notificationsHubProxy = connection.createHubProxy('NotificationsHub');
connection.qs = "userId=" + userId;
notificationsHubProxy.on('notify', function (notifications) {
notifyAll(notifications);
});
connection.start()
.done(function() {
notificationsHubProxy.invoke('getNotifications', "1,2,3");
})
.fail(function(reason) {
alert('signalr error');
});
这是一个用于实现IUserIdProvider的类,它检索querystring并返回userId,我调试了这个类和GetUserId方法,框架没有调用它。
public class RealTimeNotificationsUserIdProvider : IUserIdProvider
{
public string GetUserId(IRequest request)
{
return request.QueryString["userId"];
}
}
这是我的启动类,用于将IUserId提供程序与signalR配置挂钩:
var userIdProvider = new RealTimeNotificationsUserIdProvider();
GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => userIdProvider);
app.Map("/signalr", map =>
{
var hubConfiguration = new HubConfiguration
{
EnableDetailedErrors = true,
Resolver = dependencyResolver,
EnableJavaScriptProxies = false
};
map.RunSignalR(hubConfiguration);
});
现在,当我试图通过访问Clients向特定用户发送通知时。User(userId)不起作用:
var userId = "1";
Clients.User(userId).notify("test");
我错过了什么?请帮忙。
您所拥有的看起来应该可以工作。唯一看起来可疑的是,您正在用GlobalHost.DependencyResolver
注册IUserIdProvider
,但您的HubConfiguration中有Resolver = dependencyResolver
。
在您的问题中,没有其他地方提到dependencyResolver
。如果不使用Resolver = dependencyResolver
,SignalR默认情况下会使用GlobalHost.DependencyResolver
。
hier是我为解决这个问题所做的,形成我的请求。QueryString["userId"]没有返回用户id,这就是它不起作用的原因,我像下面这样更改了你的代码,它确实起作用,我在我的项目中测试了它:
using using System.Web;
public class RealTimeNotificationsUserIdProvider : IUserIdProvider
{
public string GetUserId(IRequest request)
{
return HttpContext.Current.User.Identity.GetUserId()
}
}
删除var userIdProvider=new RealTimeNotificationsUserIdProvider(),并如下所示编写:
ConfigureAuth(app); GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => new RealTimeNotificationsUserIdProvider()); app.Map("/signalr", map => { var hubConfiguration = new HubConfiguration { EnableDetailedErrors = true, EnableJavaScriptProxies = false }; map.RunSignalR(hubConfiguration); });