Click here to Skip to main content
15,867,686 members
Articles / Security / Identity
Tip/Trick

Displaying User Full Name instead of User Email in AspNet Identity 2.0

Rate me:
Please Sign up or sign in to vote.
4.54/5 (8 votes)
15 May 2015CPOL3 min read 101.1K   12   12
How to replace User.Identity.Name (Email) by Full Name in AspNet Identity 2.0

Introduction

AspNet Identity 2.0 with MVC 5 by default displays the username which is user's email address in  _LoginPartial.cshtml page.  I will go through how to change this to user's FirstName and LastName  i.e. Full Name

Background

AspNet Indentity 2.0 uses user email address as user name and displays it on successfull login to confirm the user by showing the partial view _LoginPartial. As default AspNet Identity 2.0 does not store user information such as first name or last name. To store and use user's First Name and Last Name, we can create new columns to the AspNetUsers table or add new table to store them by linking with the AspNetUsers table. I will follow the first approach where I will create two columns named as FirstName and LastName and use them to display the full user name after successful login. 

Description

To start with I am going to create a new  MVC 5 ASP.NET Web application in  using Visual Studio 2013.

Image 1

From the list of available templates I will choose MVC and click OK to create the project.

Image 2

When the project is created, it looks as below in the Solution Explorer:

Image 3

Before doing any change to the project, I will update the database connection string to point to my LocalDb database and change the database name to AspNetIdentity2.

 <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=AspNetIdentity2;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

As I mentioned I will add two columns FirstName and LastName to the user record while registering the user to the application.  

Currently the default registration form does not have First Name or Last Name fields.

Image 4

To add the new two fields we need to make sure that the model data validates the two new fields and they are correctly inserted to the database while the user does the registtraion.

Adding two new properties

I have added FirstName and LastName  properties to the  IdentityModels in ApplicationUser class as below:

public class ApplicationUser : IdentityUser
   {
       public string FirstName { get; set; }
       public string LastName { 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
           return userIdentity;
       }
   }

I have also added the same two properties  to the RegisterViewModel class in  AccountViewModels as below:

public class RegisterViewModel
   {
       [Required]
       [EmailAddress]
       [Display(Name = "Email")]
       public string Email { get; set; }

       [Required]
       [DataType(DataType.Text)]
       [Display(Name = "First Name")]
       public string FirstName { get; set; }

       [Required]
       [DataType(DataType.Text)]
       [Display(Name = "Last Name")]
       public string LastName { get; set; }

       [Required]
       [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
       [DataType(DataType.Password)]
       [Display(Name = "Password")]
       public string Password { get; set; }

       [DataType(DataType.Password)]
       [Display(Name = "Confirm password")]
       [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
       public string ConfirmPassword { get; set; }
   }

After that I have added two new text fields to the Registration view to capture user's FirstName and Last Name

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.FirstName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.LastName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.LastName, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Register" />
        </div>
    </div>
}

Having done these, we can see the two new fields in the Register view as below:

Image 5

Updating controller methods

I will update the POST method in Account controller where the information are saved to the database. Here I have added FirstName and LastName to save with Email and Password.

// POST: /Account/Register
       [HttpPost]
       [AllowAnonymous]
       [ValidateAntiForgeryToken]
       public async Task<ActionResult> Register(RegisterViewModel model)
       {
           if (ModelState.IsValid)
           {

               var user = new ApplicationUser
               {
                   UserName = model.Email,
                   Email = model.Email,
                   FirstName = model.FirstName,
                   LastName = model.LastName
               };

               var result = await UserManager.CreateAsync(user, model.Password);
               if (result.Succeeded)
               {
                   await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                   // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                   // Send an email with this link
                   // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                   // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                   // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                   return RedirectToAction("Index", "Home");
               }
               AddErrors(result);
           }

           // If we got this far, something failed, redisplay form
           return View(model);
       }

Before we run and register for the application, let us migrate the database with the changes for to columns.

 I have run the command from the Package Manager Console

Enable-Migrations

Image 6

After that I run the command

Add-Migration

Image 7

And finally to update the database I issued

Update-Database

Image 8

If we look at AspNetUsers table we can see two new columns which are not present in the original table as shown on the right side.

 

Image 9Image 10

Let us run and register a user to the application

Image 11

After successful registration the Home page looks as below:

Image 12

Updating code to send users' full name to the view

Now I will make changes for displaying the user's Full Name instead of the email address.

I will create a Controller class that will be the base controller for other controllers for the application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AspNetIdentity2.Models;

namespace AspNetIdentity2.Controllers
{
    public class ApplicationBaseController : Controller
    {
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (User != null)
            {
                var context = new ApplicationDbContext();
                var username = User.Identity.Name;

                if (!string.IsNullOrEmpty(username))
                {
                    var user = context.Users.SingleOrDefault(u => u.UserName == username);
                    string fullName = string.Concat(new string[] { user.FirstName, " ", user.LastName });
                    ViewData.Add("FullName", fullName);
                }
            }
            base.OnActionExecuted(filterContext);
        }
        public ApplicationBaseController()
        { }
    }
}

I have changed all controller methods to inherit the ApplicationBaseController instead of Controller.

For instance the HomeController inherits ApplicationBaseController as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AspNetIdentity2.Controllers
{
    public class HomeController : ApplicationBaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

Now I have changed the _LoginPartial.cshtml  as below to display the user's Full Name from ViewData as the ApplicationBaseController sends the full name.

HTML
@using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated && ViewData.ContainsKey("FullName"))
{
    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
    {
    @Html.AntiForgeryToken()

    <ul class="nav navbar-nav navbar-right">
        <li>
            @Html.ActionLink("Hello " + (ViewData["FullName"]) + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
        </li>
        <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
    </ul>
    }
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
        <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
    </ul>
}

Now we can see the full name is displayed.

 

Image 13

 

Points of Interest

AspNet Identity 2.0, MVC 5

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow can i display Username instead of First Name and Last Name? Pin
Pankaj Mahor3-Sep-19 5:28
Pankaj Mahor3-Sep-19 5:28 
How can i display Username instead of First Name and Last Name? Can we use above method to display Username instead of First Name and Last Name?

QuestionNice! I was looking to add an AVATAR instead of a name... Pin
Member 1394936229-Aug-18 7:47
Member 1394936229-Aug-18 7:47 
QuestionReally good guide! Pin
Pelle Källström5-Jan-16 7:29
Pelle Källström5-Jan-16 7:29 
Questionnice article but i have a question Pin
akanksha srivastava2-Dec-15 0:57
akanksha srivastava2-Dec-15 0:57 
AnswerRe: nice article but i have a question Pin
Mostafa Asaduzzaman2-Dec-15 8:36
Mostafa Asaduzzaman2-Dec-15 8:36 
QuestionAnother way of achieving this Pin
Jon Smith24-May-15 9:49
Jon Smith24-May-15 9:49 
AnswerRe: Another way of achieving this Pin
Mostafa Asaduzzaman24-May-15 10:17
Mostafa Asaduzzaman24-May-15 10:17 
AnswerRe: Another way of achieving this Pin
Member 1088081221-Jun-16 7:46
Member 1088081221-Jun-16 7:46 
AnswerRe: Another way of achieving this Pin
User 4730756-Feb-18 6:21
User 4730756-Feb-18 6:21 
GeneralRe: Another way of achieving this Pin
Swarnakamal Mishra6-Mar-20 20:13
Swarnakamal Mishra6-Mar-20 20:13 
Questionnice article Pin
Member 1170543620-May-15 3:22
Member 1170543620-May-15 3:22 
AnswerRe: nice article Pin
Mostafa Asaduzzaman20-May-15 9:16
Mostafa Asaduzzaman20-May-15 9:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.