[ASP.NET MVC]自訂Action Filter

前言:

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

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

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

自己來實作紀錄一下。

操作的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 MVC]自訂Action Filter,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。