ASP.NET Core身份-获取当前用户 [英] ASP.NET Core Identity - get current user
问题描述
要获得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控制器中:
Assuming your code is inside an MVC controller:
public class MyController : Microsoft.AspNetCore.Mvc.Controller
从Controller
基类,您可以从User
属性获得
From the Controller
base class, you can get the IClaimsPrincipal
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:
可以从数据库的用户实体中获取其他字段:
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;
这篇关于ASP.NET Core身份-获取当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!