Asp.net-Core
在 Entity Framework Core 中獲取目前使用者 ID 的正確方法
對於 ASP.NET Core 的不同 RC,關於如何獲取目前登錄使用者的 ID,這裡有很多不同的答案。我想在這裡問一個明確的問題。請注意 project.json 現在有 “Microsoft.AspNetCore.Identity.EntityFrameworkCore”: “1.0.0”
使用 RC1,您可以執行以下操作:
using Microsoft.AspNet.Identity; using System.Security.Claims; User.GetUserId();但是對於新發布的 EF Core 版本 1,Microsoft.AspNet.Identity 不是正確的版本。
有人建議使用 UserManager,這似乎只是為了獲取目前登錄的使用者:
private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User); var user = await GetCurrentUserAsync(); var userId = user?.Id;我發現的另一種方法是:
private readonly UserManager<ApplicationUser> _userManager; _userManager.GetUserId(User)那麼對於 ASP.NET Core 1 RTM 和 EF Core 1 以及 project.json 中的以下庫,獲取目前登錄使用者 id 的正確方法是什麼?
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0", "Microsoft.AspNetCore.Mvc": "1.0.0",
ASP.NET Core Identity 通過 DI 在 startup.cs 中註入 - 因此您只需通過建構子注入 UserManager
UserManager<ApplicationUser> userManager然後您可以在方法中使用以下內容
_userManager.GetUserId(User);當您使用個人使用者帳戶創建新的 ASP.NET Core 1 項目時,這就是它在範例 Web 應用程序中使用的方式。
如果您從 Controller 中訪問它,那麼使用UserManager獲取使用者 ID 效率非常低,因為您正在往返於數據庫。如果您使用ClaimsIdentity,您可以執行以下操作來獲取使用者 ID:
var claimsIdentity = (ClaimsIdentity)this.User.Identity; var claim = claimsIdentity.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier); var userId = claim.Value;此方法僅讀取 cookie 中已經存在的使用者 ID,然後自動反序列化並儲存在ClaimsIdentity實例中。
我使用這個助手類:
public static class UserHelpers { public static string GetUserId(this IPrincipal principal) { var claimsIdentity = (ClaimsIdentity)principal.Identity; var claim = claimsIdentity.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier); return claim.Value; } }因此獲取使用者 ID 變為:
var userId = this.User.GetUserId();如果由於某種原因,所需的聲明不在Claims集合中,您可以在創建使用者的ClaimsIdentity時輕鬆添加它:
public class ApplicaionUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager) { var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); userIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, this.UserId)); return userIdentity; } }