如何获取当前登录用户的详细信息?

时间:2019-02-10 13:30:41

标签: c# asp.net-mvc

我已将新属性添加到ApplictionUser,现在我想检索它?

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

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

   //....
}
  

我尝试使用User.Identity...进行检索,但是我无法获得名字和姓氏?

该怎么做?我会非常感谢

2 个答案:

答案 0 :(得分:3)

我以这种方式检索了firstName和SecondName:

第1步。

// DbContext.
private readonly ApplicationDbContext _context;

public HomeController()
{
   _context = new ApplicationDbContext();
}

第2步。

// Getting Id of Current LoggedIn User.
var UserId = User.Identity.GetUserId();

第3步。

var User = _context.Users.Single(user => user.Id == UserId);
  

这些步骤对我有用。

答案 1 :(得分:2)

User.Identity仅返回不包含任何自定义属性和System.Security.Principal.IIdentity实例的抽象ApplicationUser

其中一种选择是使用UserManager<ApplicationUser>,如果您的Startup类具有ASP.NET Core Identity的配置,则可以将其注入控制器:

var user = await _userManager.FindByIdAsync(userId);

它将完全返回ApplicationUser实例。

另一种选择是直接从您的DbContext获取用户(默认情况下,其名称为ApplicationDbContext。它也可以注入到控制器中)。

var user = await db.Users.SingleOrDefaultAsync(u => u.Id == userId);