How Can I get UserId from ConnectionId in asp.net

2019-08-15 09:54发布

I am using Asp.net Identity framework for authentication. Now I need the User id of connected client from connectionId or role of connected user.

1条回答
等我变得足够好
2楼-- · 2019-08-15 10:21
public class WhateverHub : Hub
{
    public override Task OnConnected()
    {
        //Get the username
        string name = Context.User.Identity.Name;

        //Get the UserId
        var claimsIdentity = Context.User.Identity as ClaimsIdentity;
        if (claimsIdentity != null)
        {
            // the principal identity is a claims identity.
            // now we need to find the NameIdentifier claim
            var userIdClaim = claimsIdentity.Claims
                .FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);

            if (userIdClaim != null)
            {
                var userIdValue = userIdClaim.Value;
            }
        }
        return base.OnConnected();
    }
}

Don't forget to use the [Authorize] attribute in your Hub class

查看更多
登录 后发表回答