將標準 Blazor 服務器與 Microsoft 搭建的個人帳戶一起使用,如何訪問組件內的登錄用戶 ID?.NET 5。
我試過AuthenticationStateProvider利用它來獲取它,但回傳空值。
var authState = await authenticationStateProvider.GetAuthenticationStateAsync();
if (authState.User.Identity.IsAuthenticated)
{
var id = authState.User.FindFirst(c => c.Type == "nameidentifier")?.Value;
}
uj5u.com熱心網友回復:
用戶資訊存盤在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://www.uj5u.com/net/327905.html
標籤:。网 asp.net核心 西装外套 blazor 服务器端
上一篇:是否可以使用dotnetnew創建一個ASP.NETWebApplicationEmpty.NetFramework4.7.2專案?
下一篇:Microsoft.Data.Sqlite.SqliteExceptionSQLite錯誤1:“AUTOINCREMENT只允許在INTEGERPRIMARYKEY上”
