gpt4 book ai didi

asp.net-mvc - 如何为所有 Controller 编写 Action 过滤器

转载 作者:行者123 更新时间:2023-12-03 02:24:36 24 4
gpt4 key购买 nike

这是一个示例操作过滤器。我们知道,当我们编写 Action 过滤器时,我们需要用这样的属性来装饰 Controller ,以便将它用于任何 Controller 。

我想知道是否有任何方法可以编写一个适用于所有 Controller 的操作过滤器,而我不需要用操作过滤器属性来装饰所有 Controller 。有什么想法吗?

[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());
}
}

关于asp.net-mvc - 如何为所有 Controller 编写 Action 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26033214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com