如何从asp.net身份框架SignalR中的ConnectionId获取UserId? [英] How Can I get UserId from ConnectionId in asp.net identity framework SignalR?

查看:1361
本文介绍了如何从asp.net身份框架SignalR中的ConnectionId获取UserId?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

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

别忘了在其中使用 [Authorize] 属性您的Hub

这篇关于如何从asp.net身份框架SignalR中的ConnectionId获取UserId?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆