Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC User.Identity.Name with first and last names

I have added First and Last name to the ApplicationUser Class.

 public class ApplicationUser : IdentityUser
    {
        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
            return userIdentity;
        }

        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

also added information to RegisterViewModel

My application successfully created First and LastName to the table but I am unable to get the first and last names as to display in _LoginPartial "User.Identity.Name"

like image 924
Emil Avatar asked Sep 03 '14 11:09

Emil


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.

How do you implement identity authentication in MVC?

Open a new project in Visual Studio and select Visual C#. In Visual C#, select ASP.NET Web Application and give the project name. Click OK. Step 2: Select MVC template from template type and click Change Authentication button.


1 Answers

in your partialview _LoginPartial.cshtml

Add the code:

@if (Request.IsAuthenticated)
{
    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
    var user = manager.FindById(User.Identity.GetUserId());
...
}

ApplicationDbContext = your DBContext -> Default : ApplicationDbContext

With the instance of ApplicationUser (user) you can get First- and LastName-property

Replace User.Identity.Name with user.FirstName + " " + user.LastName like this:

<ul class="nav navbar-nav navbar-right">
    <li>
        @Html.ActionLink("Hello " + user.FirstName + " " + user.LastName + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
    </li>
    <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
like image 176
Edi G. Avatar answered Oct 18 '22 10:10

Edi G.