gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:58:11 25 4
gpt4 key购买 nike

我使用 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;
}

在您的 Controller 中,您可以通过将 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 中,所以一旦您在服务器上加载并填充它们一次,您就不需要一次又一次地访问数据库来获取信息。

关于c# - 我们可以扩展 HttpContext.User.Identity 以在 asp.net 中存储更多数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32040671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com