中间件是一种装配到应用管道以处理请求和响应的软件。
通常,中间件封装在类中,并且通过扩展方法公开。
约定模式
自定义类-扩展-注册
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
/// <summary>
/// 访问接口耗时
/// </summary>
public class CustomInvokeElapseTime
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
private readonly Stopwatch _stopwatch;
public CustomInvokeElapseTime(RequestDelegate next)
{
_next = next;
_stopwatch = new Stopwatch();
}
public CustomInvokeElapseTime(RequestDelegate next, ILogger logger) : this(next)
{
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
_stopwatch.Restart();
context.Response.OnCompleted(() =>
{
_stopwatch.Stop();
#if DEBUG
Console.WriteLine($"ElaspedTime:{_stopwatch.ElapsedMilliseconds} ms");
_logger.LogInformation($"执行耗时:{_stopwatch.ElapsedMilliseconds} ms");
#endif
return Task.CompletedTask;
});
await _next(context);
}
}
/// <summary>
/// 扩展中间件
/// </summary>
public static class CustomInvokeElapseTimeExtensions
{
public static IApplicationBuilder UseCustomInvokeElapseTime(this IApplicationBuilder app)
{
return app.UseMiddleware<CustomInvokeElapseTime>();
}
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
logger.LogInformation("自定义中间件添加到管道中");
app.UseCustomInvokeElapseTime();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "XXX.dll");
});
}