简体   繁体   中英

Can we extend HttpContext.User.Identity to store more data in asp.net?

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.

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