この目的でクレームを使用できます。デフォルトの 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 に保存されるため、サーバーに一度ロードして入力すると、情報を取得するために何度もデータベースにアクセスする必要がなくなります。