我可以扩展访问用户属性的方法吗?
有以下方法:
User.Identity.GetUserId() User.Identity.GetUserName()
哪些可以从视图和控制器访问.
User.Identity.GetUserPhoneNumber() User.Identity.GetUserLanguaje()
解决方法
类似的问题:
Need access more user properties in User.Indentity由codeplex工作日的微软专业人士回答如下
“You can get the User object and do User.Email or User.PhoneNumber since these properties are hanging off the User model”
我们可以在ASP.Net身份中获取应用程序当前的User对象,从那里可以访问用户对象的所有属性,我们在mvc5网络应用程序中也是如此.
//In Account controller like this var currentUser = UserManager.FindById(User.Identity.GetUserId());
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); // Get the current logged in User and look up the user in ASP.NET Identity var currentUser = manager.FindById(User.Identity.GetUserId());
现在我们可以访问所有用户道具(电话号码和语言)如下
var phoneNumber = currentUser.PhoneNumber; var userLanguage = currentUser.Language;
编辑:如果你想在任何view.cshtml或_Layout.cshtml中检索相同,那么你应该像下面这样做
@using Microsoft.AspNet.Identity @using Microsoft.AspNet.Identity.EntityFramework @using YourWebApplication.Models @{ var phoneNumber= string.Empty; var userLanguage = string.Empty; if (User.Identity.IsAuthenticated) { var userStore = new UserStore<ApplicationUser>(new ApplicationDbContext()); var manager = new UserManager<ApplicationUser>(userStore); var currentUser = manager.FindById(User.Identity.GetUserId()); phoneNumber = currentUser.PhoneNumber; userLanguage = currentUser.Language; } }