视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
ASP.NET Core中间件计算Http请求时间示例详解
2020-11-27 22:34:28 责编:小采
文档


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

总结

下载本文
显示全文
专题