I using asp.net identity. I create the default asp.net mvc application that implement user identity. The application use HttpContext.User.Identity to retrieve user id and user name :
string ID = HttpContext.User.Identity.GetUserId();
string Name = HttpContext.User.Identity.Name;
I am able to customize AspNetUsers table. I add some properties to this table but want to be able to retrieve these properties from HttpContext.User. Is that possible ? If it is possible, how can I do it ?
You can use Claims for this purpose. The default MVC application has a method on the class representing users in the system called GenerateUserIdentityAsync
. Inside that method there is a comment saying // Add custom user claims here
. You can add additional information about the user here.
For example, suppose you wanted to add a favourite colour. You can do this by
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
userIdentity.AddClaim(new Claim("favColour", "red"));
return userIdentity;
}
Inside your controller you can access the claim data by casting User.Identity
to ClaimsIdentity
(which is in System.Security.Claims
) as follows
public ActionResult Index()
{
var FavouriteColour = "";
var ClaimsIdentity = User.Identity as ClaimsIdentity;
if (ClaimsIdentity != null)
{
var Claim = ClaimsIdentity.FindFirst("favColour");
if (Claim != null && !String.IsNullOrEmpty(Claim.Value))
{
FavouriteColour = Claim.Value;
}
}
// TODO: Do something with the value and pass to the view model...
return View();
}
Claims are good because they are stored in cookies so once you've loaded and populated them once on the server, you don't need to hit the database again and again to get at the information.