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

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

我使用 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/

相关文章:

c# - 如何捕获 "A potentially dangerous Request.Path value was detected from the client (:)"以避免 Web 角色崩溃?

asp.net-identity - ASP.NET 标识 : Why User Properties AND Claims?

c# - 在 MVC 应用程序上自动执行防伪 token 验证

c# - User.IsInRole() 返回 false 并且授权角色给我拒绝访问

c# - 起订量返回设置在第二次执行时返回错误数据

c# - 使用 C# 从 Mettler Toledo (IND560) 秤设备读取数据

c# - 多次指定固定名称 System.Data.SqlClient 的提供程序

C# - 具有托管服务身份的 Azure 存储

javascript - 带有 jquery ui 选项卡的 MVC 4

asp.net-mvc - 确保 View 存在