欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET Core中间件计算Http请求时间示例详解

程序员文章站 2023-10-23 21:24:53
asp.net core通过requestdelegate这个委托类型来定义中间件 public delegate task requestdelegate(ht...

asp.net core通过requestdelegate这个委托类型来定义中间件

public delegate task requestdelegate(httpcontext context);

可将一个单独的请求委托并行指定为匿名方法(称为并行中间件),或在类中对其进行定义。可通过use,或在middleware类中配置要传递给委托执行的方法(参数类型httpcontext,返回值类型task)。

public static iapplicationbuilder use(this iapplicationbuilder app, func<httpcontext, func<task>, task> middleware);

public static iapplicationbuilder usemiddleware<tmiddleware>(this iapplicationbuilder app, params object[] args);

通过定义一个中间件类 来计算http请求的时间,例:

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);
  }
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。