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

1 signalr asp.net-mvc-5 asp.net-identity asp.net-identity-2

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

Flo*_*cal 5

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

不要忘记[Authorize]Hub类中使用该属性