我在AspNetUsers
表中添加了一個名爲CompanyName
的新列。我正在尋找在我的API中使用這個查詢。MVC6身份自定義字段檢索
我已經使用了[Authorized]
屬性得到
User.Identity.Name
這顯然得到了用戶的名稱。我正在尋找一種方法來獲得CompanyName
。
我必須直接查詢aspnetusers
表才能獲取此信息嗎?
我在AspNetUsers
表中添加了一個名爲CompanyName
的新列。我正在尋找在我的API中使用這個查詢。MVC6身份自定義字段檢索
我已經使用了[Authorized]
屬性得到
User.Identity.Name
這顯然得到了用戶的名稱。我正在尋找一種方法來獲得CompanyName
。
我必須直接查詢aspnetusers
表才能獲取此信息嗎?
您需要創建一個用戶實例才能訪問用戶的屬性,我使用UserManager類來創建用戶。可能還有其他方法來完成這個任務,但這是我過去所做的。
在控制器類的頂部:
private Microsoft.AspNet.Identity.UserManager<YourApplication.Models.ApplicationUser> um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));//new up a UserManager
現在的動作方法內
:
public ActionResult Index()
{
ApplicationUser user = um.FindById(User.Identity.GetUserId());//Create an instance of the user
ViewBag.CompanyName = user.CompanyName ;//Read the property
return View();
}
以下方法將幫助你把custom data。 如果這沒有幫助,請提供更多信息。就像您創建的位置或您檢索位置的源代碼一樣。
string username = HttpContext.Current.User.Identity.Name;
var identity = new MyIdentity(username, true);
var principal = new MyPrincipal(identity, identity.Roles);
HttpContext.Current.User = principal;