ASP.NET Core中间件计算Http请求时间
2019-06-15 18:32
1666 查看
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); } }
相关文章推荐
- 学习ASP.NET Core, 怎能不了解请求处理管道[5]: 中间件注册可以除了可以使用Startup之外,还可以选择StartupFilter
- 一:理解ASP.NET的运行机制(例:通过HttpModule来计算页面执行时间)
- 通过重建Hosting系统理解HTTP请求在ASP.NET Core管道中的处理流程[上]:采用管道处理请求
- 如何测量并报告ASP.NET Core Web API请求的响应时间
- Asp.Net Core IIS发布后PUT、DELETE请求错误405.0 - Method Not Allowed 因为使用了无效方法(HTTP 谓词)
- 一:理解ASP.NET的运行机制(例:通过HttpModule来计算页面执行时间)
- 学习ASP.NET Core,你必须知道“中间件”是什么?中间件如何注册?请求处理管道是如何通过中间件构建的?
- ASP.NET Core 2.2 基础知识(十二) 发送 HTTP 请求
- ASP.NET Core 使用 URL Rewrite 中间件实现 HTTP 重定向到 HTTPS
- 一:理解ASP.NET的运行机制(例:通过HttpModule来计算页面执行时间)
- 通过重建Hosting系统理解HTTP请求在ASP.NET Core管道中的处理流程[中]:管道如何处理请求
- ASP.NET Core应用针对静态文件请求的处理[4]: DirectoryBrowserMiddleware中间件如何呈现目录结构
- 通过重建Hosting系统理解HTTP请求在ASP.NET Core管道中的处理流程[下]:管道是如何构建起来的?
- asp.net 通过httpModule计算页面的执行时间
- 学习ASP.NET Core,怎能不了解请求处理管道[1]: 中间件究竟是个什么东西?
- ASP.NET Core应用针对静态文件请求的处理[5]: DefaultFilesMiddleware中间件如何显示默认页面
- 学习ASP.NET Core,怎能不了解请求处理管道[1]: 中间件究竟是个什么东西?
- ASP.NET Core应用针对静态文件请求的处理[3]: StaticFileMiddleware中间件如何处理针对文件请求
- ASP.NET页面请求超时时间设置多种方法
- 详解ASP.NET Core 中间件之压缩、缓存