【问题标题】:How can I get my own User in controller in Asp.net core mvc如何在 Asp.net core mvc 的控制器中获取自己的用户
【发布时间】:2019-05-17 08:11:56
【问题描述】:

我有用户类:

public class User : Entity
{

    public void AcceptMenu(Menu menu)
    {
      //AcceptMenu 
    }      
    public string Login { get; set; }
    public string Password { get; set; }
    public string Salt { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

我创建了授权逻辑。验证方法如下所示:

      private async Task Authenticate(User user)
    {

        var claims = new List<Claim>
        {
            new Claim(ClaimsIdentity.DefaultNameClaimType, user.Login),
            new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role)
        };

        ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);

        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(id));
    }

如您所见,我在 User 中有 AcceptMenu 方法。如何在 Controller 中获取 User 并执行 AcceptMenu 方法?

【问题讨论】:

  • @AntonToshik,哪个函数?

标签: c# asp.net-mvc asp.net-core


【解决方案1】:

Controller 具有 IPrincipal 类型的属性 User。您可以使用User.Identity.Name 获取用户名称,但它是经过身份验证的 asp.net 用户的名称。您可以将此 Authenticated 用户映射到您的用户类。 在控制器中

ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

ApplicationUser  user = await UserManager.FindByEmailAsync(User.Identity.Name);

其中 ApplicationUserManager 是具有身份配置的类,而 ApplicationUser 是此类中的 IdentityUser。但它不是你的实体类派生的db用户,应该手动映射

【讨论】:

  • 你是否建议让用户喜欢:var user = appContext.Users.Single(a =&gt; a.Login == User.Identity.Name);
  • 是的,这是正确的方法,你也可以使用 [dbo].[AspNetUsers] 但它不是可扩展的方法
【解决方案2】:

如果您已登录,您可以随时使用var loggedInUser = await useManager.GetUserAsync(User) 获取用户。

【讨论】:

    【解决方案3】:

    How to get the current logged in user Id in ASP.NET Core 从 ClaimsPricipal 获取值后,您可以将该值作为参数传递。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-18
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多