ASP.NET Core Identity - 获取当前用户 [英] ASP.NET Core Identity - get current user

查看:109
本文介绍了ASP.NET Core Identity - 获取当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在 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:

  1. 使用依赖注入获取用户管理器

  1. 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 - 获取当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆