未针对userid和connectionid映射调用SignalR IUserIdProvider

时间:2014-09-27 08:12:14

标签: javascript c# asp.net signalr signalr-hub

我正在通过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的类,它检索查询字符串并以userId形式返回,我调试了这个类,并且框架没有调用GetUserId方法。

 public class RealTimeNotificationsUserIdProvider : IUserIdProvider
{
    public string GetUserId(IRequest request)
    {
      return  request.QueryString["userId"];
    }
}

这是我的启动类,用于连接带有signalR配置的IUserId提供程序:

      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");
我错过了什么?请帮忙。

2 个答案:

答案 0 :(得分:0)

你看起来应该有什么用。唯一看起来可疑的是您使用IUserIdProvider注册了GlobalHost.DependencyResolver,但是您的HubConfiguration中有Resolver = dependencyResolver

您问题中的其他地方没有其他dependencyResolver引用。如果您遗漏Resolver = dependencyResolver,SignalR默认会使用GlobalHost.DependencyResolver

答案 1 :(得分:0)

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