アクション フィルター

# カスタム アクション フィルタ

さまざまな理由から、カスタム アクション フィルターを作成します。ロギング用、またはアクション実行前にデータをデータベースに保存するためのカスタム アクション フィルタがある場合があります。データベースからデータをフェッチし、それをアプリケーションのグローバル値として設定するためのものもあるでしょう。

カスタム アクション フィルターを作成するには、次のタスクを実行する必要があります。

<オール>
  • クラスを作成する
  • ActionFilterAttribute クラスから継承
  • 次のメソッドの少なくとも 1 つをオーバーライドします:

    OnActionExecuting – このメソッドは、コントローラー アクションが実行される前に呼び出されます。

    OnActionExecuted – このメソッドは、コントローラー アクションが実行された後に呼び出されます。

    OnResultExecuting – このメソッドは、コントローラー アクションの結果が実行される前に呼び出されます。

    OnResultExecuted – このメソッドは、コントローラー アクションの結果が実行された後に呼び出されます。

    以下のリストに示すように、フィルタを作成できます:

    
       using System;
        
        using System.Diagnostics;
        
        using System.Web.Mvc;
        
        
        
        namespace WebApplication1
        {
        
            public class MyFirstCustomFilter : ActionFilterAttribute
            {
                public override void OnResultExecuting(ResultExecutingContext filterContext)
                {
                    //You may fetch data from database here 
                    filterContext.Controller.ViewBag.GreetMesssage = "Hello Foo";
                    base.OnResultExecuting(filterContext);
                }
        
                public override void OnActionExecuting(ActionExecutingContext filterContext)
                {
                    var controllerName = filterContext.RouteData.Values["controller"];
                    var actionName = filterContext.RouteData.Values["action"];
                    var message = String.Format("{0} controller:{1} action:{2}", "onactionexecuting", controllerName, actionName);
                    Debug.WriteLine(message, "Action Filter Log");
                    base.OnActionExecuting(filterContext);
                }
            }
        }