如何为所有控制器编写动作过滤器

编程入门 行业动态 更新时间:2024-10-09 08:34:42
本文介绍了如何为所有控制器编写动作过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是一个示例动作过滤器.我们知道,当编写动作过滤器时,我们需要用这样的属性装饰控制器,以将其用于任何控制器.

Here is a sample action filter. We know that when we write an action filter then we need to decorate the controller with an attribute like this, to use it for any controller.

我想知道是否有任何方式可以编写一个动作过滤器,该动作过滤器对所有控制器都适用,而我不需要用动作过滤器属性来装饰所有控制器.有什么想法吗?

I like to know whether there is any way to write an action filter which will work for all controllers in way that I do not need to decorate all the controllers with an action filter attribute. Any ideas?

[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}", methodName, controllerName, actionName); Debug.WriteLine(message, "Action Filter Log"); } } public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalFilters.Filters.Add(new LogActionFilterAttribute()); } }

更多推荐

如何为所有控制器编写动作过滤器

本文发布于:2023-11-17 11:09:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609820.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:过滤器   何为   控制器   动作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!