How Can I get UserId from ConnectionId in asp.net identity framework SignalR?

雨燕双飞 提交于 2019-12-24 17:43:30

问题


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:


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



来源:https://stackoverflow.com/questions/37065582/how-can-i-get-userid-from-connectionid-in-asp-net-identity-framework-signalr

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