Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User.Identity.Name full name mvc5

I've extended the ASP NET identity schema by adding few fields in the ApplicationUser Class which is derived from IdentityUser. One of the field that I've added is FullName.

Now, when I write User.Identity.Name, it gives me the user name, I m looking for something like User.Identity.FullName which should return the FullName that I have added.

Not sure, how this can be achieved any guidance shall be greatly appreciated.

Thanks.

like image 731
Ashish Charan Avatar asked Jan 26 '14 11:01

Ashish Charan


People also ask

What is user identity name in MVC?

User.Identity.Name is going to give you the name of the user that is currently logged into the application.

What is HttpContext user identity name?

It just holds the username of the user that is currently logged in. After login successful authentication, the username is automatically stored by login authentication system to "HttpContext.Current.User.Identity.Name" property.

What is Microsoft AspNet identity?

ASP.NET Identity is Microsoft's user management library for ASP.NET. It includes functionality such as password hashing, password validation, user storage, and claims management. It usually also comes with some basic authentication, bringing its own cookies and multi-factor authentication to the party.


1 Answers

In the ApplicationUser class, you'll notice a comment (if you use the standard MVC5 template) that says "Add custom user claims here".

Given that, here's what adding FullName would look like:

public class ApplicationUser : IdentityUser {     public string FullName { get; set; }      public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)     {         // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType         var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);         // Add custom user claims here         userIdentity.AddClaim(new Claim("FullName", this.FullName));         return userIdentity;     } } 

Using this, when someone logs in, the FullName claim will be put in the cookie. You could make a helper to access it like this:

    public static string GetFullName(this System.Security.Principal.IPrincipal usr)     {         var fullNameClaim = ((ClaimsIdentity)usr.Identity).FindFirst("FullName");         if (fullNameClaim != null)             return fullNameClaim.Value;          return "";     } 

And use the helper like this:

@using HelperNamespace ... @Html.ActionLink("Hello " + User.GetFullName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" }) 

Note that custom user claims are stored in the cookie and this is preferable to getting the user info from the DB... saves a DB hit for commonly accessed data.

like image 150
Marcel Avatar answered Sep 29 '22 04:09

Marcel