ASP.NET Core Identity

编程入门 行业动态 更新时间:2024-10-11 13:21:17
本文介绍了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:

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

  • 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

    本文发布于:2023-11-17 09:03:57,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1609556.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:NET   ASP   Identity   Core

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!