5

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

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

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

4

1 回答 1

8

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

于 2015-08-17T05:33:02.567 回答