ASP. NET Core Middleware Calculating Http Request Time Example Detailed Explanation

  • 2021-11-10 09:15:03
  • OfStack

ASP. NET Core defines middleware through the delegate type RequestDelegate


public delegate Task RequestDelegate(HttpContext context);

A single request delegate can be specified in parallel as an anonymous method (called parallel middleware) or defined in a class. You can configure the methods (parameter type HttpContext, return value type Task) to be passed to the delegate through Use or in the Middleware class.


public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware);

public static IApplicationBuilder UseMiddleware<TMiddleware>(this IApplicationBuilder app, params object[] args);

Calculate the time of http request by defining 1 middleware class, for example:


public class ResponseTimeMiddleware
{
  // Name of the Response Header, Custom Headers starts with "X-" 
  private const string RESPONSE_HEADER_RESPONSE_TIME = "X-Response-Time-ms";
  // Handle to the next Middleware in the pipeline 
  private readonly RequestDelegate _next;
  public ResponseTimeMiddleware(RequestDelegate next)
  {
    _next = next;
  }
  public Task InvokeAsync(HttpContext context)
  {
    // Start the Timer using Stopwatch 
    var watch = new Stopwatch();
    watch.Start();
    context.Response.OnStarting(() => {
      // Stop the timer information and calculate the time  
      watch.Stop();
      var responseTimeForCompleteRequest = watch.ElapsedMilliseconds;
      // Add the Response time information in the Response headers.  
      context.Response.Headers[RESPONSE_HEADER_RESPONSE_TIME] = responseTimeForCompleteRequest.ToString();
      return Task.CompletedTask;
    });
    // Call the next delegate/middleware in the pipeline  
    return this._next(context);
  }
}

Summarize


Related articles: