要在 MVC5 中获取当前登录的用户,我们要做的就是:
To get the currently logged in user in MVC5, all we had to do was:
using Microsoft.AspNet.Identity; [Authorize] public IHttpActionResult DoSomething() { string currentUserId = User.Identity.GetUserId(); }现在,使用 ASP.NET Core 我认为这应该可以工作,但它会引发错误.
Now, with ASP.NET Core I thought this should work, but it throws an error.
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Http; private readonly UserManager<ApplicationUser> _userManager; [HttpPost] [Authorize] public async Task<IActionResult> StartSession() { var curUser = await _userManager.GetUserAsync(HttpContext.User); }有什么想法吗?
Gerardo 的回复正常,但要获取用户的实际ID",这似乎有效:
Gerardo's response is on track but to get the actual "Id" of the user, this seems to work:
ClaimsPrincipal currentUser = this.User; var currentUserID = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value; 推荐答案如果您的代码在 MVC 控制器中:
public class MyController : Microsoft.AspNetCore.Mvc.Controller从 Controller 基类,您可以从 User 属性获取 ClaimsPrincipal
From the Controller base class, you can get the ClaimsPrincipal from the User property
System.Security.Claims.ClaimsPrincipal currentUser = this.User;您可以直接检查索赔(无需往返数据库):
You can check the claims directly (without a round trip to the database):
bool isAdmin = currentUser.IsInRole("Admin"); var id = _userManager.GetUserId(User); // Get user id:可以从数据库的 User 实体中获取其他字段:
Other fields can be fetched from the database's User entity:
使用依赖注入获取用户管理器
Get the user manager using dependency injection private UserManager<ApplicationUser> _userManager; //class constructor public MyController(UserManager<ApplicationUser> userManager) { _userManager = userManager; }
并使用它:
And use it:
var user = await _userManager.GetUserAsync(User); var email = user.Email;如果你的代码是一个服务类,你可以使用依赖注入来获取一个IHttpContextAccessor,让你从HttpContext中获取User.
If your code is a service class, you can use dependency injection to get an IHttpContextAccessor that lets you get the User from the HttpContext.
private IHttpContextAccessor _httpContextAccessor; public MyClass(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } private void DoSomething() { var user = _httpContextAccessor.Context?.User; }更多推荐
ASP.NET Core Identity
发布评论