首页 > Web开发 > 详细

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

时间:2019-09-06 13:50:07      阅读:81      评论:0      收藏:0      [点我收藏+]

ASP.NET Core通过RequestDelegate这个委托类型来定义中间件

1
public delegate Task RequestDelegate(HttpContext context);

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

1
2
3
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请求的时间,例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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);
  }
}

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

原文:https://www.cnblogs.com/nutyziug045/p/11474299.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!