简体   繁体   中英

User.Identity.Name or GetUserName not working on MVC 5

I'm working on an MVC system where I have achieved to put the log in view as the initial page to show (like a splash screen) and once the users have successfully log in redirect them to the main view.

What I need to do next is:

  1. One the users are in the main view, there is a section where I try to show the user name. For example: John Smith. To achieve this I'm using the following:

     User.Identity.Name 

    or

     User.Identity.GetUserName 

But none of them seems to work. The name is not displayed. Looking into the tables that were generated when I created my MVC project from VS, AspNetUser table doesn't have any column for the Name, last name or full name. Instead it has some columns and one of them is UserName which store the data like this: john.smith .

So, in order to display the Name and last name of the user should I created extra column on that table and update the register view to enter those kind of data?

Thanks in advance

First of all if you have properly set up ASP .NET Identity or if you are using project starter template which comes with ASP .NET Identity then following should work in the View:

@User.Identity.Name

@User.Identity.GetUserName()

Also If you want to add custom properties to your user then you will have to add those properties to ApplicationUser class or any other class inherited by IdentityUser and then use that class in IdentityDbContext ...

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }
}

Check this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM