Storing User On Login then Pushing Data On Demand

给你一囗甜甜゛ 提交于 2019-12-03 14:11:04

问题


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 connection from .js located in my masterpage. That will assign this use a specific userId.

Let's say now user B logs in goes does some event and that event needs to notify user A from codebehind.

So what I am trying to do here is notify user B of use A's action from CodeBehind. How will user B know user A's ID and how does the whole thing work? I couldn't find help in the documentation as it does not go into that kind of stuff.

How can this be achieved? Thanks.


回答1:


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!




回答2:


Your app needs to store a mapping of SignalR client (connection) IDs to user ids/names. That way, you can look up the current SignalR client ID for user B and then use it to send a message directly to them. Look at the chat sample app at https://github.com/davidfowl/JabbR for an example of this.



来源:https://stackoverflow.com/questions/8130132/storing-user-on-login-then-pushing-data-on-demand

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!