如何在asp.net身份框架SignalR中从ConnectionId获取UserId?

时间:2016-05-06 06:17:52

标签: asp.net-mvc-5 signalr asp.net-identity asp.net-identity-2

我正在使用Asp.net Identity框架进行身份验证。 现在我需要来自connectionId的连接客户端的用户ID或连接用户的角色。

1 个答案:

答案 0 :(得分:3)

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

请勿忘记使用Hub课程中的[Authorize]属性