Search code examples
asp.net-core-2.0middlewareasp.net-core-webapirequest-pipeline

how to write Middleware to measure request processing time in asp.net core 2.0


I need to use a third part tool to measure the time taken to process each request in API. My code will be something like below,

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

I need to add this code in all controllers and methods. How can I create a middleware to do this? So that I don't need to add this code in all the methods.

Here my custom tool will send the time taken to process the request to an engine, which we use for our matrices.


Solution

  • With ASP.NET Core it could be as simple as (in Startup.Configure()):

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

    The order or added middleware matters here, make sure you put your call before app.UseMvc().