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

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

问题描述

一个MVC 4应用程序的一些用户遇到零星缓慢。 presumably不是每个用户每次发生在他们身上的时间报道了这个问题。

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

我的想法是衡量每个控制器动作所花费的时间和日志超过prescribed时间,以方便进一步的分析行动调用的细节(在排除或排除服务器/ code问题)。

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).

有钩在执行这样的测量,因此,我能避免增加仪表code到每个操作方便的方法?我不是目前使用国际奥委会的这个项目,并会毫不犹豫地介绍它正好解决了这一问题。

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

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()过滤器提供商

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

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

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