测量调用 ASP.NET MVC 控制器操作的时间 [英] Measure Time Invoking ASP.NET MVC Controller Actions

查看:24
本文介绍了测量调用 ASP.NET MVC 控制器操作的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MVC 4 应用程序的某些用户偶尔会遇到缓慢的情况.大概不是每个用户每次遇到这个问题时都会报告这个问题.

Some users of an MVC 4 app are experiencing sporadic slowness. Presumably not every user reports that problem every time it happens to them.

我的想法是测量每个控制器操作所花费的时间,并记录超过规定时间的操作调用的详细信息,以便进一步分析(排除或排除服务器/代码问题).

My thought is to measure the time spent in each controller action and log details of action invocations that exceed a prescribed time to facilitate further analysis (to rule in or rule out a server/code issue).

是否有一种方便的方法可以挂钩来执行此类测量,以便我可以避免向每个操作添加检测代码?我目前没有在这个项目中使用 IOC,为了解决这个问题,我会犹豫引入它.

Is there a convenient way to hook in to perform such measurements so that I can avoid adding instrumentation code to each action? I'm not currently using IOC for this project and would hesitate to introduce it just to solve this issue.

有没有更好的方法来解决这类问题?

Is there a better way to tackle this type of problem?

推荐答案

您能否创建一个全局操作过滤器?像这样:

Could you create a global action filter? Something like this:

public class PerformanceTestFilter : IActionFilter
{
    private Stopwatch stopWatch = new Stopwatch();

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        stopWatch.Reset();
        stopWatch.Start();
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        stopWatch.Stop();
        var executionTime = stopWatch.ElapsedMilliseconds;
        // Do something with the executionTime
    }
}

然后将其添加到您在Application_Start()"中的 GlobalFilters 集合

and then add it to your GlobalFilters collection in `Application_Start()'

GlobalFilters.Filters.Add(new PerformanceTestFilter());

您可以从 filterContext 参数中获取有关正在测试的控制器的详细信息.

You can get details about the controller being tested from the filterContext parameter.

更新

直接将过滤器添加到 GlobalFilters 集合将为所有操作创建过滤器的单个实例.当然,这不适用于计时并发请求.要为每个操作创建一个新实例,请创建一个过滤器提供程序:

Adding the filter to the GlobalFilters collection directly will create a single instance of the filter for all actions. This, of course, will not work for timing concurrent requests. To create a new instance for each action, create a filter provider:

public class PerformanceTestFilterProvider : IFilterProvider
{
    public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        return new[] {new Filter(new PerformanceTestFilter(), FilterScope.Global, 0)};
    }
}

然后不是直接添加过滤器,而是在Application_Start()中添加过滤器提供者:

Then instead of adding the filter directly, rather add the filter provider in Application_Start():

FilterProviders.Providers.Add(new PerformanceTestFilterProvider());

这篇关于测量调用 ASP.NET MVC 控制器操作的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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