【问题标题】:Can we extend HttpContext.User.Identity to store more data in asp.net?我们可以扩展 HttpContext.User.Identity 以在 asp.net 中存储更多数据吗?
【发布时间】:2015-11-09 12:23:50
【问题描述】:

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

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

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

【问题讨论】:

标签: c# asp.net-mvc asp.net-identity asp.net-identity-3


【解决方案1】:

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

【讨论】:

  • 感谢您的回答。无法使您的答案正确的一个问题是我想存储动态数据而不是静态数据。例如,我想存储当前用户的图片 url。如果我可以获得用户 ID,我可以向数据库发出请求以获取图片 url 并将其存储在声明中。在 public async Task GenerateUserIdentityAsync 方法中,我无法访问 HttpContext.Current.User.Identity.GetUserId()。它始终为空。你能解决这个问题吗?
  • 我找到了一种获取用户 ID (this.id) 的方法。感谢您的解决方案。偏离路线 +1
  • 太好了,很高兴听到这有帮助!我还要指出,您不仅限于仅从 GenerateUserIdentityAsync 方法内部填充声明。您也可以在代码的其他部分添加和删除声明。为此,您需要创建一个new ClaimsIdentity(User.Identity),然后根据需要添加或删除声明。
  • 再次感谢。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-04
  • 2021-05-08
  • 1970-01-01
  • 2021-12-23
  • 2018-11-05
  • 1970-01-01
相关资源
最近更新 更多