繁体   English   中英

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

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

我使用asp.net身份。 我创建了实现用户身份的默认asp.net mvc应用程序。 该应用程序使用HttpContext.User.Identity来检索用户ID和用户名:

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

我可以自定义AspNetUsers表。 我在这个表中添加了一些属性,但希望能够从HttpContext.User中检索这些属性。 那可能吗 ? 如果有可能,我该怎么办?

您可以将声明用于此目的。 默认的MVC应用程序在类上有一个方法,表示系统中名为GenerateUserIdentityAsync用户。 在该方法中有一条评论说// Add custom user claims here 您可以在此处添加有关用户的其他信息。

例如,假设您要添加喜欢的颜色。 你可以这样做

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

在您的控制器中,您可以通过将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();
}

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

暂无
暂无

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

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