如何从 asp.net 身份框架 SignalR 中的 ConnectionId 获取 UserId?
How Can I get UserId from ConnectionId in asp.net identity framework SignalR?
我正在使用 Asp.net 身份验证框架。
现在我需要来自 connectionId 的已连接客户端的用户 ID 或已连接用户的角色。
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
class
中使用 [Authorize]
属性
我正在使用 Asp.net 身份验证框架。 现在我需要来自 connectionId 的已连接客户端的用户 ID 或已连接用户的角色。
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
class
[Authorize]
属性