「ASP.NET MVC/フィルター」の版間の差分
imported>Administrator |
imported>Fallout New Tokyo |
||
| (2人の利用者による、間の3版が非表示) | |||
| 1行目: | 1行目: | ||
[[ASP.NET MVC]]の'''フィルター'''とは、コントローラークラスやアクションメソッド(コントローラークラスのメソッド)に、[[属性]](Attribute)もちいて処理を挿入する機能のことである。 | [[ASP.NET MVC]]の'''フィルター'''とは、コントローラークラスやアクションメソッド(コントローラークラスのメソッド)に、[[属性]](Attribute)もちいて処理を挿入する機能のことである。 | ||
== 使い道の例 == | |||
[[アクション]]ごとにユーザー認証処理が「されている」「されていない」などの処理を書いていたのでは面倒、かつ本流ではない[[ソースコード]]が入りまくり見通しが悪くなるのでフィルター化しておくと便利だという。 | |||
たとえばEditアクションはログインしているユーザーのみ使えるとする場合は、以下のようにEditアクションにAuthorizeフィルター(アトリビュート)を付ける。 | |||
<source lang="csharp"> | <source lang="csharp"> | ||
[Authorize] | [Authorize] | ||
| 17行目: | 17行目: | ||
== フィルターの種類 == | == フィルターの種類 == | ||
[[ASP.NET MVC]] | [[ASP.NET MVC]]のフィルターは大きく分けて、承認フィルター、アクションフィルター、結果フィルター、例外フィルターの4つに分けられる。 | ||
=== 承認フィルター === | === 承認フィルター === | ||
| 74行目: | 74行目: | ||
[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Method, Inherited = true, AllowMultiple = true)] | [AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Method, Inherited = true, AllowMultiple = true)] | ||
public class AuthorizeAttribute | public class AuthorizeAttribute | ||
: FilterAttribute, | : FilterAttribute, // FilterAttributeを継承して | ||
IAuthorizationFilter | IAuthorizationFilter // IAuthorizationFilterを実装する | ||
{ | { | ||
//... | //... | ||
| 88行目: | 88行目: | ||
public override void OnActionExecuting(ActionExecutingContext filterContext) | public override void OnActionExecuting(ActionExecutingContext filterContext) | ||
{ | { | ||
filterContext.HttpContext.Trace.Write("(Logging Filter)Action Executing: " | filterContext.HttpContext.Trace.Write( | ||
filterContext.ActionDescriptor.ActionName); | "(Logging Filter)Action Executing: " | ||
+ filterContext.ActionDescriptor.ActionName); | |||
base.OnActionExecuting(filterContext); | base.OnActionExecuting(filterContext); | ||
| 98行目: | 99行目: | ||
{ | { | ||
if (filterContext.Exception != null) | if (filterContext.Exception != null) | ||
{ | |||
filterContext.HttpContext.Trace.Write("(Logging Filter)Exception thrown"); | filterContext.HttpContext.Trace.Write("(Logging Filter)Exception thrown"); | ||
} | |||
base.OnActionExecuted(filterContext); | base.OnActionExecuted(filterContext); | ||
| 107行目: | 110行目: | ||
== 関連項目 == | == 関連項目 == | ||
* [[ASP.NET MVC]] | * [[ASP.NET MVC]] | ||
** [[ASP.NET MVC/セレクター]] | |||
== 参考文献 == | == 参考文献 == | ||
{{reflist}} | |||
{{stub}} | {{stub}} | ||