我们可以扩展 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 table。我向此 table 添加了一些属性,但希望能够从 HttpContext.User 检索这些属性。那可能吗 ?如果可以,我该怎么做?

您可以为此目的使用声明。默认 MVC 应用程序在 class 上有一个方法,代表系统中的用户,称为 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 中,所以一旦您在服务器上加载并填充它们一次,您就不需要一次又一次地访问数据库来获取信息。