Storing User On Login then Pushing Data On Demand

后端 未结 2 1966
南笙
南笙 2021-02-06 19:06

So I\'m using SignalR, it\'s setup and working correctly on my Website.

Let\'s suppose user A logs in (I am using the Membership API). When A logs in I am calling the co

2条回答
  •  醉梦人生
    2021-02-06 19:21

    I realize this has already been answered, but there another option that folks might find helpful. I had trouble finding info on how to do this, so hopefully this helps someone else.

    You can override the SignalR ClientID generation and make it use the membership UserID. This means you do not have to maintain a CleintID -> UserID mapping.

    To do this, you create a class that implements the IClientIdFactory interface. You can do something like:

    public class UserIdClientIdFactory : IClientIdFactory
    {
        public string CreateClientId(HttpContextBase context)
        {
            // get and return the UserId here, in my app it is stored
            // in a custom IIdentity object, but you get the idea
            MembershipUser user = Membership.GetUser();
            return user != null ? 
                 user.ProviderUserKey.ToString() : 
                 Guid.NewGuid().ToString();
        }
    }
    

    And then in your global.asax:

    SignalR.Infrastructure.DependencyResolver.Register(typeof(IClientIdFactory), () => new UserIdClientIdFactory());
    

    EDIT -- as nillls mentioned below, things have changed in the signalR version 0.4. Use ConnectionId rather than ClientId:

    public class UserIdClientIdFactory : IConnectionIdFactory
    {
        public string CreateConnectionId(SignalR.Hosting.IRequest request)
        {
            // get and return the UserId here, in my app it is stored
            // in a custom IIdentity object, but you get the idea
            MembershipUser user = Membership.GetUser();
            return user != null ? 
                 user.ProviderUserKey.ToString() : 
                 Guid.NewGuid().ToString();
        }
    }
    

    And DependencyResolver has moved:

    SignalR.Hosting.AspNet.AspNetHost.DependencyResolver.Register(typeof(IConnectionIdFactory), () => new UserIDClientIdFactory());
    

    Hope this helps someone!

提交回复
热议问题