ASP.NET Identity Extend methods to access user properties

爷,独闯天下 提交于 2020-01-01 08:46:47

问题


As I can extend methods to access user properties?

There are methods like:

User.Identity.GetUserId()
User.Identity.GetUserName()

Which are accessible from the views and the controllers.

I want to extend this functionality with methods like:

User.Identity.GetUserPhoneNumber()
User.Identity.GetUserLanguaje()

回答1:


Similar Question: Need access more user properties in User.Indentity answered by Microsoft professionals at codeplex worklog as below

"You can get the User object and do User.Email or User.PhoneNumber since these properties are hanging off the User model"

We can get the application current User object in ASP.Net identity as below, from there you can access all properties of user object, we follow the same in mvc5 web-apps as of now.

//In Account controller like this
var currentUser = UserManager.FindById(User.Identity.GetUserId());

In other controllers you will need to add the following to your controller:

  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()); 

Now we can access all user props(Phone# and Language) as below

var phoneNumber = currentUser.PhoneNumber;
var userLanguage = currentUser.Language;

EDIT: If you want to retrieve the same in any view.cshtml or _Layout.cshtml then you should do like below

@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;
    }
}


来源:https://stackoverflow.com/questions/26836169/asp-net-identity-extend-methods-to-access-user-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!