【问题标题】:how to write Middleware to measure request processing time in asp.net core 2.0如何在 asp.net core 2.0 中编写中间件来测量请求处理时间
【发布时间】:2018-08-23 10:48:04
【问题描述】:

我需要使用第三方工具来衡量处理 API 中每个请求所花费的时间。我的代码如下所示,

 [HttpGet("{id}")]
 public string Get(int id)
 {
    using (SomeTool.Start.Measuring)
    {
       //Do the process
       return "somevalue";
    }
 }

我需要在所有控制器和方法中添加此代码。 我怎样才能创建一个中间件来做到这一点?这样我就不需要在所有方法中添加这段代码了。

在这里,我的自定义工具会将处理请求所花费的时间发送到一个引擎,我们将其用于我们的矩阵。

【问题讨论】:

    标签: asp.net-core-2.0 middleware asp.net-core-webapi request-pipeline


    【解决方案1】:

    使用 ASP.NET Core,它可以像 (Startup.Configure()) 一样简单:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //  ...
    
        app.Use(async (context, next) =>
        {
            using (SomeTool.Start.Measuring)
            {
                await next.Invoke();
            }
        });
    
        app.UseMvc();
    }
    

    这里的顺序或添加的中间件很重要,请确保您在app.UseMvc()之前拨打电话。

    【讨论】:

      猜你喜欢
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      • 2018-08-24
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多