【问题标题】:How to access the authenticated & authorized User details?如何访问经过身份验证和授权的用户详细信息?
【发布时间】:2018-12-17 14:57:55
【问题描述】:

例如:

我有一个简单的应用程序!

并且默认实现了简单的用户注册页面和登录页面(当我们选择mvc tempate时)。

所以我为用户注册模型添加了新属性。 像这样。

public class ApplicationUser : IdentityUser
{
    [Required]
    [StringLength(255)]
    public string FirstName { get; set; }

    [Required]
    [StringLength(50)]
    public string LastName { get; set; }

    [Required]
    [StringLength(10)]
    public string Gender { get; set; }

    [Required]
    [StringLength(50)]
    public UserType UserType { get; set; }

    [Required]
    [StringLength(255)]
    public Department Depatment{ get; set; }

    [Required]
    [StringLength(50)]
    public Session Session { get; set; }
}

这些属性也被添加到RegisterViewModel中,用于渲染注册页面等等..

问题:

当新用户注册时!并登录应用程序。 所以现在我想访问登录的用户详细信息? 即名字、姓氏、性别等。

我试过User.Identity.?,但没有这样的属性?之前我添加到 ApplicationUser ?

我想访问所有 LoggedIn 用户属性并将其呈现在视图中。

[Authorize]
public ActionResult Index()
{
    // Retreiving LoggedIn User Details.
    // ....
    // ....
    // LoggedInUserInfo = // assigning all the User details to the LoggedUserInfo

    return View(LoggedInUserInfo); // LoggedInUserInfo is a separete class that having several properties such as firstName, lastName, Gener, etc...
}

【问题讨论】:

  • 你的“ApplicationUser”在哪里被持久化了?
  • ~/Models/IdentityModels.cs 在 identity.cs 文件中

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


【解决方案1】:

您可以注入 UserManager 类,然后使用它来获取应用程序用户信息。

private UserManager<ApplicationUser> _userManager;
public YourController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}

它们在你的方法中:

var user = await _userManager.GetUserAsync(User);
var firstName = user.FirstName;
var lastName = user.LastName;
var middleName = user.MiddleName;
var documentNumber = user.DocumentNumber;

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    结合你的ApplicationDbContext和扩展方法GetUserId()你可以找到登录的ApplicationUser

    ApplicationUser loggedInUser = applicationDbContext.Users.Find(HttpContext.User.Identity.GetUserId());
    

    【讨论】:

    • HttpContext.Current ?当前无法访问?我必须包含哪个命名空间?
    • @Rehan.S 我已经编辑了我的答案,因为Current 在这种情况下确实是错误的。另请注意,如果您能够在控制器中注入依赖项,abarrenechea 的解决方案也是一个不错的解决方案。
    猜你喜欢
    • 2020-09-11
    • 1970-01-01
    • 2019-06-20
    • 2011-05-23
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 2011-05-30
    • 2011-02-05
    相关资源
    最近更新 更多