看看源爲GetUserId
擴展方法:
/// <summary>
/// Return the user id using the UserIdClaimType
/// </summary>
/// <param name="identity"></param>
/// <returns></returns>
public static string GetUserId(this IIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
var ci = identity as ClaimsIdentity;
if (ci != null)
{
return ci.FindFirstValue(ClaimTypes.NameIdentifier);
}
return null;
}
/// <summary>
/// Return the claim value for the first claim with the specified type if it exists, null otherwise
/// </summary>
/// <param name="identity"></param>
/// <param name="claimType"></param>
/// <returns></returns>
public static string FindFirstValue(this ClaimsIdentity identity, string claimType)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
var claim = identity.FindFirst(claimType);
return claim != null ? claim.Value : null;
}
每次調用擴展方法它將搜索ClaimTypes.NameIdentifier
要求的身份。
性能影響不是那麼重要(IMO),但在隱藏中泄漏用戶信息(如果只需點擊view source
就可以看到它們,那麼實際上並沒有隱藏)不是一個好主意。
如果您擔心多次調用它,需要它在多個位置通過了一個請求,那麼你可以把它裝懶在控制器中性能或基幕後控制人。
private string userId
public string UserId {
get {
if(userid == null) {
userid = User.Identity.GetUserId();
}
return userid;
}
}
您也可以創建一個服務來封裝該信息。