【问题标题】:How Can I get UserId from ConnectionId in asp.net identity framework SignalR?如何从 asp.net 身份框架 SignalR 中的 ConnectionId 获取 UserId?
【发布时间】:2016-09-01 03:01:16
【问题描述】:

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

【问题讨论】:

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


    【解决方案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();
        }
    }
    

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

    【讨论】:

    • 我需要来自 connectionID 的用户 ID 吗?你知道你在信号器中的connectionId吗?我的意思是任何连接的客户端都有一个唯一的连接 ID,我需要那些 coectiondId 用户 ID?你明白我的意思吗?
    • SignalR ConnectiondIdIdentity UserIdUsers 表中的主键)不相同。你需要什么?
    • 谢谢 :) 它现在的作品 :) 你能帮我解决另一个问题吗?
    • 我想在任何管理员用户在线时激活聊天室。如果任何管理员用户不在线,则任何用户都无法聊天。我该怎么做你能帮我吗?
    • 这太宽泛了。我不知道“聊天室”对你来说是什么,但我假设它是一个 SignalR 组。您需要做的是跟踪所有连接的用户以及他们是否是管理员 (using OnConnected, OnDisconnected and OnReconnected)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 2014-08-07
    • 2018-06-17
    • 2014-01-21
    相关资源
    最近更新 更多