我已将新属性添加到ApplictionUser
,现在我想检索它?
public class ApplicationUser : IdentityUser
{
[Required]
[StringLength(50)]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
public string LastName { get; set; }
//....
}
我尝试使用
User.Identity...
进行检索,但是我无法获得名字和姓氏?
该怎么做?我会非常感谢。
答案 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);