[ASP.NET MVC]自訂Action Filter

前言:

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

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

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

自己來實作紀錄一下。

[ASP.NET MVC]自訂Action Filter_第1张图片

操作的Action Filter Log

继承自ActionFIleter, 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,这次尝试一下异步的Action,来改善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));
        }
   .....
}


实验结果:

 

 

你可能感兴趣的:(asp.net)