ASP.NET Core經過RequestDelegate這個委託類型來定義中間件app
public delegate Task RequestDelegate(HttpContext context);
可將一個單獨的請求委託並行指定爲匿名方法(稱爲並行中間件),或在類中對其進行定義。可經過Use,或在Middleware類中配置要傳遞給委託執行的方法(參數類型HttpContext,返回值類型Task)。ui
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請求的時間,例:this
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); } }