简体   繁体   English

我们可以扩展HttpContext.User.Identity在asp.net中存储更多数据吗?

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

I using asp.net identity. 我使用asp.net身份。 I create the default asp.net mvc application that implement user identity. 我创建了实现用户身份的默认asp.net mvc应用程序。 The application use HttpContext.User.Identity to retrieve user id and user name : 该应用程序使用HttpContext.User.Identity来检索用户ID和用户名:

string ID = HttpContext.User.Identity.GetUserId();
string Name = HttpContext.User.Identity.Name;

I am able to customize AspNetUsers table. 我可以自定义AspNetUsers表。 I add some properties to this table but want to be able to retrieve these properties from HttpContext.User. 我在这个表中添加了一些属性,但希望能够从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 . 默认的MVC应用程序在类上有一个方法,表示系统中名为GenerateUserIdentityAsync用户。 Inside that method there is a comment saying // Add custom user claims here . 在该方法中有一条评论说// 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 在您的控制器中,您可以通过将User.Identity强制转换为ClaimsIdentity (位于System.Security.Claims )来访问声明数据,如下所示

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. 声明是好的,因为它们存储在cookie中,因此一旦您在服务器上加载并填充它们一次,您就不需要再次访问数据库来获取信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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