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()
IdentityDbContext() Initializes a new instance of the IdentityDbContext class. IdentityDbContext(DbContextOptions) Initializes a new instance of IdentityDbContext.
It contains default properties such as username, email, password e.t.c. This class can be inherited and more properties provided. IdentityRole is the ASP.NET Core MVC class that contains information about user roles (which are usage domains) of the IdentityUsers defined in your application.
ASP.NET Core Identity provides a framework for managing and storing user accounts in ASP.NET Core apps. Identity is added to your project when Individual User Accounts is selected as the authentication mechanism. By default, Identity makes use of an Entity Framework (EF) Core data model.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With