【问题标题】:ASP.NET Core measure performance [closed]ASP.NET Core 测量性能 [关闭]
【发布时间】:2018-02-16 08:42:57
【问题描述】:

我需要测量我的 ASP.NET Core 应用程序的性能。更具体地说,完成单个 HTTP 请求所需的时间。

我现在这样做的方式是在我的代码周围使用Stopwatch 实例:

并将结果返回到标准输出。

编辑

您可以想象,这种方法分布在不同的应用程序部分,而最好将其隔离(例如单独的类)以便更容易维护。

衡量 ASP.NET Core 应用程序性能的最佳方法是什么?

谢谢。

【问题讨论】:

  • 我投票结束,因为这里要求提出建议的主题。出于对话的兴趣:您是否查看过任何针对 ASP.NET Core 的预构建性能监控工具?
  • 嗨@john,感谢您的回复,但我不确定我是否理解您的观点:正如我的问题所述,我正在寻找最优雅的方法来衡量 ASP.NET Core 中 HTTP 请求的性能因为框架似乎没有提供开箱即用的功能。

标签: c# asp.net performance asp.net-core .net-core


【解决方案1】:

您可以使用 asp.net filter pipeline 实现 ActionLogFilter。

    public class ActionLogFilter : IActionFilter
{
    // some dependencies
    private DateTime traceStart;
    private readonly Stopwatch stopwatch;

    public ActionLogFilter(// some dependencies)
    {
        this.stopwatch = new Stopwatch();
    }

    // here the action starts executing
    public void OnActionExecuting(ActionExecutingContext context)
    {
        this.traceStart = DateTime.UtcNow;
        this.stopwatch.Start();
    }

    // here the action is executed
    public void OnActionExecuted(ActionExecutedContext context)
    {
        this.stopwatch.Stop();
        var traceEnd = this.traceStart
                       .AddMilliseconds(this.stopwatch.ElapsedMilliseconds);
        // do something, persist it somewhere if necessary
    }
}

现在你可以继续你的启动类并添加注册过滤器

public void ConfigureServices(IServiceCollection services) 
{
   .....
   services.AddMvc(options => options.Filters.Add(typeof(ActionLogFilter));
   .....
}

如果您需要该操作日志过滤器中的更多信息,例如有关请求控制器、路径等的信息,您可以使用您最喜欢的 IoC-Container 注册IHttpContextAccesor。对于原生 DI,请执行以下操作

public void ConfigureServices(IServiceCollection services) 
{
   .....
   services.AddScoped<IHttpContextAccessor, HttpContextAccesor>();
   .....
}

然后您可以将依赖项注入过滤器并通过 property of the IHttpContextAccessor 实例访问 HttpContext。

如果您希望该过滤器异步运行,则可以改为实现 IAsyncActionFilter

【讨论】:

    猜你喜欢
    • 2015-01-29
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 2017-10-12
    • 2018-07-23
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    相关资源
    最近更新 更多