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