User.Identity.Name full name mvc5

匿名 (未验证) 提交于 2019-12-03 02:14:01

问题:

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.

回答1:

You could add it to the User's claims when you create the user and then retrieve it as a claim from the User.Identity:

await userManager.AddClaimAsync(user.Id, new Claim("FullName", user.FullName)); 

Retreive it:

((ClaimsIdentity)User.Identity).FindFirst("FullName") 

Or you could just fetch the user and access it off of the user.FullName directly:

var user = await userManager.FindById(User.Identity.GetUserId()) return user.FullName 


回答2:

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.



回答3:

I have found that this works pretty well

AccountController:

private async Task SignInAsync(ApplicationUser user, bool isPersistent)     {         AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);         var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);         identity.AddClaim(new Claim("FullName", user.FullName));         identity.AddClaim(new Claim("Email", user.Email));         identity.AddClaim(new Claim("DateCreated", user.DateCreated.ToString("MM/dd/yyyy")));         AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);     } 

Extension Method on Identity:

 public static class GenericPrincipalExtensions {     public static string FullName(this IPrincipal user)     {         if (user.Identity.IsAuthenticated)         {             ClaimsIdentity claimsIdentity = user.Identity as ClaimsIdentity;             foreach (var claim in claimsIdentity.Claims)             {                 if (claim.Type == "FullName")                     return claim.Value;             }             return "";         }         else             return "";     } } 

In your View:

 @Html.ActionLink("Hello " + User.FullName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" }) 

You can look at the thread here: Link



回答4:

It is possible by defining your own IIdentity (and possibly IPrincipal too) and constructing this when creating the IPrincipal for the HTTP request (when PostAuthenticateRequest is raised).

How to implement your own IIDentity and IPrincipal: How do I implement custom Principal and Identity in ASP.NET MVC?



回答5:

I solved the problem by doing the following:

1 - Create my own CustomPrincipal by extending IPrincipal

2 - Load the CustomPrincipal after each request has been authenticated.

Create my own CustomPrincipal

interface ICustomPrincipal : IPrincipal {     string UserId { get; set; }     string FirstName { get; set; }     string LastName { get; set; }     int CustomerId { get; set; } }  public partial class CustomPrincipal : ClaimsPrincipal, ICustomPrincipal {     #region IPrincipal Members     public new ClaimsIdentity Identity { get; private set; }     public new bool IsInRole(string role)     {         IdentityManager manager = new IdentityManager();         return manager.IsInRole(role, this.UserId);     }     #endregion      public CustomPrincipal(ApplicationUser user, IIdentity identity)         :base(identity)     {         this.Identity = new ClaimsIdentity(identity);         this.UserId = user.Id;         this.FirstName = user.FirstName;         this.LastName = user.LastName;         this.CustomerId = user.CustomerId;         this.DateCreated = user.DateCreated;     }      #region ICustomPrinicpal Members     public string UserId { get; set; }     public string FirstName { get; set; }     public string LastName { get; set; }     public int CustomerId { get; set; }     public DateTime DateCreated { get; set; }     #endregion      public string GetFullName()     {         return this.FirstName + " " + this.LastName;     } } 

Load the CustomPrincipal after each request has been authenticated

In the Global.asax.cs...

    protected void Application_PostAuthenticateRequest(object sender, EventArgs e)     {         if (User.Identity.IsAuthenticated)         {             //At this point we need to get the user from the database based on the username.              ApplicationUser AppUser = ApplicationUserDB.GetByUserName(User.Identity.Name);             CustomPrincipal UserPrincipal = new CustomPrincipal(AppUser, User.Identity);             HttpContext.Current.User = UserPrincipal;         }     } 

As you can see in my code above, I retrieve an ApplicationUser and pass it in the constructor of the CustomPrincipal. I then assign the new CustomPrincipal to the current context.



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