Search code examples
c#asp.netasp.net-identity-2

Getting additional fields with Identity 2.0 in Layout page


I have an issue that I assumed would be a simple fix, but has turned into a big problem.

On my _Layout.cshtml page, I just want to display the current user's first and last name. This is stored in the AspNetUsers database table in the Name column. I currently have this on the layout page:

<h5>@Context.User.Identity.Name</h5>

This just displays the Username for that user, and Name is the only property available. Is there a way to overload the Identity to expose the user's full name?

This wouldn't be a big issue if it was only on one page, then I could just load that user data in the controller, but it needs to be shared across all pages in the layout.


Solution

  • Check if the information is stored as claims. Then you can access it via the claims identity like this:

    @((ClaimsIdentity)Context.User.Identity).FindFirstValue("fullnameclaimname");
    

    If the claim does not exist (check the Claims property of the ClaimsIdentity) you can add it when you authenticate the user in the GenerateUserIdentityAsync of the ApplicationUser class. In this method you generate the ClaimsIdentity from an ApplicationUser.