【问题标题】:Does Indentiy in ASP.NET MVC core provide an easy way to access the UserId from any page ?ASP.NET MVC 核心中的 Indentiy 是否提供了一种从任何页面访问 UserId 的简便方法?
【发布时间】:2018-08-29 20:02:06
【问题描述】:

或者我是否需要在 ASP.NET 中设置会话并获取用户 ID 并像...一样手动传递它?

  public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;

        //Save UserId in session
        HttpContext.Session.SetString("UserIdKey", "123");
        ViewData["UserId"] = HttpContext.Session.GetString("UserIdKey");

....

【问题讨论】:

标签: asp.net-mvc session asp.net-core asp.net-identity


【解决方案1】:

使用扩展

    public static class IdentityExtension
    {
        public static string GetId(this IIdentity identity)
        {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;

            Claim claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

            return claim.Value;
        }
    }

示例

User.Identity.GetId()

【讨论】:

    【解决方案2】:

    假设你注入了一个UserManager,截至2.1 you can use

    string userid = _userManager.GetUserId(userPrincipal);
    

    userPrincipal 可以由ControllerBase.User Property 提供。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      相关资源
      最近更新 更多