如何从Blazor服务器登录userId



使用Microsoft提供的标准Blazor服务器和个人帐户,我如何访问组件内部的登录userId ?5 . net .

我试过进入AuthenticationStateProvider并使用它来获得它,但返回null。

var authState = await authenticationStateProvider.GetAuthenticationStateAsync();
if (authState.User.Identity.IsAuthenticated)
{
var id = authState.User.FindFirst(c => c.Type == "nameidentifier")?.Value;
}

用户信息存储在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 );