Asp.net
如何在 Identity 3.0 中獲取目前的 UserId?User.GetUserId 返回 null
我需要獲取提出某些請求的使用者的 ID。在以前的 Identity 版本中,我可以這樣做:
User.Identity.GetUserId();但它似乎不再可用。
還有類似的東西:
User.GetUserId();但它總是返回 null,即使 User.Identity.IsAuthenticated 為 true 並且 User.Identity.Name 設置正確。
我應該用什麼來做到這一點?
編輯:我的身份驗證邏輯基於$$ default Visual Studio 2015 template $$,到目前為止我的身份沒有太大變化,所以如果你想檢查它是如何完成的,你可以在我粘貼的 github 連結上簡單地看到它。
我認為在以前的版本中有一個內置的擴展方法,但他們刪除了它。您可以實現自己的來替換它:
using System; using System.Security.Claims; using Microsoft.AspNet.Identity; namespace cloudscribe.Core.Identity { public static class ClaimsPrincipalExtensions { public static string GetUserId(this ClaimsPrincipal principal) { if (principal == null) { throw new ArgumentNullException(nameof(principal)); } var claim = principal.FindFirst(ClaimTypes.NameIdentifier); return claim != null ? claim.Value : null; } } }ClaimType.NameIdentifier 應該映射到使用者 ID
@喬·奧德特
原來它已經搬到其他地方了。
User.GetUserId => UserManager.GetUserId(User) User.GetUserName => UserManager.GetUserName(User) User.IsSignedIn => SignInManager.IsSignedIn(User)