Adding and Referencing Additional Data in the Asp.net Identity AspNetUsers Table

I have talked about Identity and how useful it is. There are somethings that I wish were included that are not however. This is when the ability to extend or modify Identity comes in useful. Storing a user’s name or other personal information in the AspNetUsers table is one of those things. In this post I am going to show how to add a FirstName and LastName column to the AspNetUsers table and then pull that information out when a user signs in.

To add the FirstName and LastName columns to the AspNetUsers table we simply add two properties to the ApplicationUser class in the Models/IdentityModels.cs file

public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
// Code Omitted for Brevity
}

By simply doing this Identity will create a FirstName and LastName column in the AspNetUsers table when the Identity tables are built out. Once the columns are there we also need to allow users to enter their first and last name when they are registering, thus we need to modify the registration functionality to allow for this.

In the RegisterViewModel class of the Models/AccountViewModel.cs file we simply add the FirstName and LastName properties with the appropriate data attributes.

public class RegisterViewModel
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
// Code Omitted for Brevity
}

We now need to add the form fields to the Views/Account/Register.cshtml file.

<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>

Finally we add the FirstName and LastName fields to the ApplicationUser constructor parameters in the HttpPost version of the Register method in the Controllers/accountController.cs file

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { FirstName=model.FirstName, LastName=model.LastName, UserName = model.Email, Email = model.Email };
// Code Omitted for Brevity
}
}

At this point we can run the application and register a new user. The form will allow us to enter our first and last name and will insert those values into the AspNetUsers table when it creates our new user record. So once that information is in the database how do we get it back out to use it? For commonly used fields like name fields we can retrieve those records when a user logs in and store them in session variables for easy access anywhere on our site.

We retrieve the values in the HttpPost version of the Login method located in the Controllers/AccountController.cs file. We start off by creating an instance of the UserManager object and then use that object to create a user object for the user that just logged in. We can then set our session variables for first and last name in the success case of the following switch statement.

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
// Code Omitted for Brevity
var userManager = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = userManager.FindByEmail(model.Email);
switch (result)
{
case SignInStatus.Success:
Session["FirstName"] = user.FirstName;
Session["LastName"] = user.LastName;
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
// Code Omitted for Brevity
}
}

Once the names are stored in the session objects we can simply output those on any view by using razor

<h1>@Session["FirstName"] @Session["LastName"]
<h1>

Finally when a user logs out we want the session variables discarded as well. We can use the clear() method of the session object to do this in the LogOff() method of the Controllers/AccountControllers.cs file.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut();
Session.Clear();
return RedirectToAction("Index", "Home");
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s