我怎么可以拦截在MVC应用程序控制器的所有电话? [英] How can I intercept all controller calls in an MVC application?

查看:133
本文介绍了我怎么可以拦截在MVC应用程序控制器的所有电话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有拦截在MVC-3控制器的所有呼叫的快速方法?

Is there a quick method for intercepting all controller calls in MVC-3?

有关记录和测试目的,我想建立一个工具,它可以拦截所有控制器调用,并记录该控制器是所谓的,与信息,在什么时间。

For logging and testing purposes, I'd like to build a tool that can intercept all controller calls, and log which controller was called, with which message, at what time.

推荐答案

我不记得在那里我得到这个从,但我四处寻找类似的东西了一段时间后,发现包含在此日志文章或一些地方过滤器:

I can't remember where I got this from, but I was looking around for something similar a while back and found an article or something somewhere that contained this logging filter:

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

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

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        Log("OnResultExecuting", filterContext.RouteData);
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        Log("OnResultExecuted", 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");
    }
}

要使用它,只需将其添加到全局过滤器在Global.asax中:

To use it, just add it to the global filters in global.asax:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new LogActionFilter());
}

我要看看现在,看看我能找到源头。

I'll have a look now to see if I can find the source.

编辑:发现了它。这是从这个问题

这篇关于我怎么可以拦截在MVC应用程序控制器的所有电话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆