asp.net-mvc – 如何为所有控制器编写动作过滤器

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 如何为所有控制器编写动作过滤器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是一个smaple动作过滤器,我们知道当我们编写动作过滤器时,我们需要像这样装饰控制器来为任何特定的控制器实现它,但是我想知道有没有办法编写动作过滤器,它将适用于所有控制器,我不需要用动作过滤器属性来装饰控制器.任何的想法.
[LogActionFilter]
public class HomeController : Controller
{}

public class LogActionFilter : ActionFilterAttribute

     {
          public override void OnActionExecuting(ActionExecutingContext filterContext)
          {
               Log("OnActionExecuting",filterContext.RouteData);       
          }

          public override void OnActionExecuted(ActionExecutedContext filterContext)
          {
               Log("OnActionExecuted",filterContext.RouteData);       
          }

          private void Log(string methodName,RouteData routeData)
          {
               var controllerName = routeData.Values["controller"];
               var actionName = routeData.Values["action"];
               var message = String.Format("{0} controller:{1} action:{2}",methodName,controllerName,actionName);
               Debug.WriteLine(message,"Action Filter Log");
          }

     }

解决方法

public class LogActionFilterAttribute : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            Log("OnActionExecuted",filterContext.RouteData);    
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Log("OnActionExecuting",filterContext.RouteData);  
        }

        private void Log(string methodName,RouteData routeData)
        {
            var controllerName = routeData.Values["controller"];
            var actionName = routeData.Values["action"];
            var message = String.Format("{0} controller:{1} action:{2}",actionName);
            Debug.WriteLine(message,"Action Filter Log");
        }
    }

public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalFilters.Filters.Add(new LogActionFilterAttribute());
        }
    }

猜你在找的asp.Net相关文章