[英]How to get current logged-In User details?
我向ApplictionUser
添加了新屬性,現在我要檢索它?
public class ApplicationUser : IdentityUser
{
[Required]
[StringLength(50)]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
public string LastName { get; set; }
//....
}
我嘗試使用
User.Identity...
進行檢索User.Identity...
但是我無法獲得名字和姓氏?
怎么做 ? 我將非常感激 。
我以這種方式檢索了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();
第三步
var User = _context.Users.Single(user => user.Id == UserId);
這些步驟對我有用。
User.Identity
僅返回不包含任何自定義屬性和ApplicationUser
實例的抽象System.Security.Principal.IIdentity
。
選項之一是使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.