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