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

本文关键字:存储 数据 net asp 扩展 HttpContext User Identity 我们 | 更新日期: 2023-09-27 18:08:07

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

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

我可以自定义AspNetUsers表。我向该表添加了一些属性,但希望能够从HttpContext.User检索这些属性。这可能吗?如果可能的话,我该怎么做呢?

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

您可以使用Claims来实现此目的。默认的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中,因此一旦在服务器上加载并填充它们,就不需要一次又一次地访问数据库来获取信息。