Ahm*_*mel 5 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;
Run Code Online (Sandbox Code Playgroud)
我可以自定义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;
}
Run Code Online (Sandbox Code Playgroud)
在您的控制器内,您可以通过强制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();
}
Run Code Online (Sandbox Code Playgroud)
声明是好的,因为它们存储在cookie中,因此一旦您在服务器上加载并填充它们一次,您就不需要再次访问数据库来获取信息.