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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 如何为所有控制器编写动作过滤器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是一个smaple动作过滤器,我们知道当我们编写动作过滤器时,我们需要像这样装饰控制器来为任何特定的控制器实现它,但是我想知道有没有办法编写动作过滤器,它将适用于所有控制器,我不需要用动作过滤器属性来装饰控制器.任何的想法.
  1. [LogActionFilter]
  2. public class HomeController : Controller
  3. {}
  4.  
  5. public class LogActionFilter : ActionFilterAttribute
  6.  
  7. {
  8. public override void OnActionExecuting(ActionExecutingContext filterContext)
  9. {
  10. Log("OnActionExecuting",filterContext.RouteData);
  11. }
  12.  
  13. public override void OnActionExecuted(ActionExecutedContext filterContext)
  14. {
  15. Log("OnActionExecuted",filterContext.RouteData);
  16. }
  17.  
  18. private void Log(string methodName,RouteData routeData)
  19. {
  20. var controllerName = routeData.Values["controller"];
  21. var actionName = routeData.Values["action"];
  22. var message = String.Format("{0} controller:{1} action:{2}",methodName,controllerName,actionName);
  23. Debug.WriteLine(message,"Action Filter Log");
  24. }
  25.  
  26. }

解决方法

  1. public class LogActionFilterAttribute : IActionFilter
  2. {
  3. public void OnActionExecuted(ActionExecutedContext filterContext)
  4. {
  5. Log("OnActionExecuted",filterContext.RouteData);
  6. }
  7.  
  8. public void OnActionExecuting(ActionExecutingContext filterContext)
  9. {
  10. Log("OnActionExecuting",filterContext.RouteData);
  11. }
  12.  
  13. private void Log(string methodName,RouteData routeData)
  14. {
  15. var controllerName = routeData.Values["controller"];
  16. var actionName = routeData.Values["action"];
  17. var message = String.Format("{0} controller:{1} action:{2}",actionName);
  18. Debug.WriteLine(message,"Action Filter Log");
  19. }
  20. }
  21.  
  22. public class MvcApplication : System.Web.HttpApplication
  23. {
  24. protected void Application_Start()
  25. {
  26. GlobalFilters.Filters.Add(new LogActionFilterAttribute());
  27. }
  28. }

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