最佳答案
要获得 MVC5中当前登录的用户,我们所要做的就是:
using Microsoft.AspNet.Identity;
[Authorize]
public IHttpActionResult DoSomething() {
string currentUserId = User.Identity.GetUserId();
}
现在,对于 ASP.NET Core,我认为这应该可以工作,但它抛出了一个错误。
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);
}
有什么想法吗?
EDIT: 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;