如何在ASP.NET Core中获取当前登录的用户标识

直到ASP.NET Core 1.0 RC1:

它是System.Security.Claims命名空间中的User.GetUserId().

自ASP.NET Core 1.0 RC2:

您现在必须使用UserManager.您可以创建一个方法来获取当前用户:

private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);

并获取对象的用户信息:

var user = await GetCurrentUserAsync();

var userId = user?.Id;
string mail = user?.Email;


ASP.NET Core 2.1和2.2中的更新:

在控制器中:

public class YourControllerNameController : Controller
{
    public IActionResult YourMethodName()
    {
        var userId =  User.FindFirstValue(ClaimTypes.NameIdentifier) // will give the user's userId
        var userName =  User.FindFirstValue(ClaimTypes.Name) // will give the user's userName
        var userEmail =  User.FindFirstValue(ClaimTypes.Email) // will give the user's Email
    }
}

在其他一些课程中:

public class OtherClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    public OtherClass(IHttpContextAccessor httpContextAccessor)
    {
       _httpContextAccessor = httpContextAccessor;
    }

   public void YourMethodName()
   {
      var userId = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
   }
}

然后你应该IHttpContextAccessorStartup课堂上注册如下:

public void ConfigureServices(IServiceCollection services)
{
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    // Or you can also register as follows

    services.AddHttpContextAccessor();
}



posted @ 2022-10-15 12:45  .net&new  阅读(631)  评论(0编辑  收藏  举报