[C#][ASP.NET MVC]自訂Action Filter

  • 9133
  • 0
  • C#
  • 2010-03-23

[C#][ASP.NET MVC]自訂Action Filter

ASP.NET MVC中了解Action Filter算滿重要的,因為操作Action Filter是最能展現MVC在設計上的特性,

而ASP.NET MVC framework提供了四種不同類型的Action Filter,每種類型都實做了相關介面,

當我們要自訂相關類型的Action Filter也相當簡單,只要透過Inherits ActionFilterAttribute就可達到,

自己來實作紀錄一下。

The Different Types of Filters

image

實作Action Filter Log

繼承ActionFilterAttribute,IActionFilter,IResultFilter

 public class LogAttibute:ActionFilterAttribute,IActionFilter,IResultFilter
    {
        public override void OnActionExecuted( ActionExecutedContext filterContext )
        {
            ThreadPool.QueueUserWorkItem( delegate
            {
                try
                {
                    String message =
                        String.Format(
                            "Method=[{0}], Action=[{1}], Controller=[{2}], IPAddress=[{3}]" +
                            "TimeStamp=[{4}]",
                            "OnActionExecuted",
                            filterContext.RouteData.Values[ "action" ] as String,
                            filterContext.Controller.ToString(),
                            filterContext.HttpContext.Request.UserHostAddress,
                            filterContext.HttpContext.Timestamp );
 
                    Log( message );
                }
                catch
                {
                     //do something
                }
                finally
                {
                    //do something
                }
            } );
        }              
 
     .......
 
 private void Log( String message )
        {    
           Debug.WriteLine( message, "Action Filter Log" );
        }  

 

 

由於操作Action Filter是同步執行的,所以這裡我套用Asynchronous Fire and Forget pattern來改善Server回應Client時間。

 

Controller

 [HandleError]
    [LogAttibute]
    public class HomeController : Controller
    {
        ASSETEntities db = new ASSETEntities();
       
        public ActionResult Index()
        {
            ViewData[ "Message" ] = "Welcome to ASP.NET MVC!";
            var q = from tbl in db.MONITOR
                    select tbl;
            return View(q.Take(10));
        }
   .....
}

 

 

結果

image

image

 

 

參考

Creating Custom Action Filters

Asynchronous .NET "Fire and Forget" Pattern

Understanding Action Filters