2009年10月13日火曜日

カスタムActionFilter その2

前回は認証を必要とするActionFilterを解説したが、今回はロールに準拠した動作をするカスタムActionFilterを解説する。

例として求人サイトを挙げる。求人サイトには求職者=Candidateと雇用者=Employerの2種類のユーザーロールが存在するものとする。そして、両者に共通の複数のページ(例:ホームページ、会社情報ページなど)があるものとし、それらのMasterPageをそれぞれのロールに準拠したものに変更したい場合の処理を下記に実装する。

-RoleBaseMasterPageAttribute.cs-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class RoleBaseMasterPageAttribute : ActionFilterAttribute
{
public RoleBaseMasterPageAttribute()
  : base()
{
   EmployerMasterPage = "~/Views/Shared/Employer.Master";
   CandidateMasterPage = "~/Views/Shared/Candidate.Master";
   AnonymousMasterPage = "~/Views/Shared/Site.Master";
}
 
public string EmployerMasterPage { get; set; }
public string CandidateMasterPage { get; set; }
public string AnonymousMasterPage { get; set; }
 
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
   ViewResult viewResult = filterContext.Result as ViewResult;
   if (viewResult == null)
     return;
 
   if (!filterContext.HttpContext.Request.IsAuthenticated)
  {
     viewResult.MasterName = AnonymousMasterPage;
  }
   else if (filterContext.HttpContext.User.IsInRole("Candidate"))
  {
     viewResult.MasterName = CandidateMasterPage;
  }
   else
  {
     viewResult.MasterName = EmployerMasterPage;
  }
}
}

これをActionまたはController全体に付与すれば、ログインしているユーザーのロールに準拠したマスターページを表示することができる。

0 件のコメント:

コメントを投稿