使用标准Blazor服务器和微软搭建的个人帐户,如何访问组件内部登录的userId?.NET 5.
我尝试过使用AuthenticationStateProvider并使用它来获取它,但是返回了null。
var authState = await authenticationStateProvider.GetAuthenticationStateAsync();
if (authState.User.Identity.IsAuthenticated)
{
var id = authState.User.FindFirst(c => c.Type == "nameidentifier")?.Value;
}发布于 2021-10-20 16:20:39
用户信息存储在ClaimsPrincipal中。下面是我使用的几个扩展方法:
public static long GetUserId( this ClaimsPrincipal principal )
{
string val = principal.FindFirstValue( ClaimTypes.NameIdentifier );
return long.Parse( val );
}
public static bool TryGetUserId( this ClaimsPrincipal principal, out long userId )
{
if( principal.HasClaim( x => x.Type == ClaimTypes.NameIdentifier ) )
{
userId = principal.GetUserId();
return true;
}
userId = -1;
return false;
}用法大概是这样的:
// from a controller
long id = User.GetUserId();
// from an HTTPContext, i.e., middleware
bool hasId = context.User.TryGetUserId( out long userId );https://stackoverflow.com/questions/69649204
复制相似问题