ASP.NET Core中间件计算Http请求时间

Posted rohmeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ASP.NET Core中间件计算Http请求时间相关的知识,希望对你有一定的参考价值。

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中间件计算Http请求时间的主要内容,如果未能解决你的问题,请参考以下文章

学习ASP.NET Core,怎能不了解请求处理管道[1]: 中间件究竟是个什么东西?

[netcore] ASP.NET Core 中间件

[netcore] ASP.NET Core 中间件

在 ASP.NET Core 中使用 HTTP 标头传播

理解ASP.NET Core

ASP.NET Core管道深度剖析:管道是如何处理HTTP请求的?