I use ASP.NET Identity 2.0 and MVC. I need to logged user's name,surname,email etc.. in view. How can get it? I can get just @User.Identity but there no my user class's property.
//in my view, i need here my ApplicationUser class
<div>
@User.Identity.Name
</div>
//ApplicationUser class
public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole,
CustomUserClaim>
{
public ApplicationUser()
{
this.CreatedDate = DateTime.Now;
}
public DateTime CreatedDate { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string TaxOffice { get; set; }
}
In case you using .NET Core app:
You can easily use the
@inject
feature call for injecting bothUserManager
andSignInManager
.In your view add the following:
After the injection, you should be able to work with
UserManager
andSignInManager
methods. For instance:Hope this will be handy for anyone :)
There are two ways you can achieve this.
1) Create your own
CustomPrincipal
by inheritingIPrincipal
interface to includeName
,Surname
andEmail
using this example or this one.2) Get details directly from the database and pass it as a model to the view.
Method one will be good option if you want to use same user details in several views, but method two is the simplest way to achieve this. let me know if you need any code help for the second method.
If there are only specific properties that you need to get, you can add them as claims in your ApplicationUser class like the following example:
This gets wired up from the Startup.Auth class:
Then, you can access the claim (in a view or in a controller):
No forms authentication tickets here.
If you want the full user details available, you could always create an extension method like the following:
And call it like this:
I would recommend caching if you're calling this all this time, however.
to get information about the user from the controller you must use
or if you want to get information about the user within your class