diff --git a/ZR.Admin.WebApi/Program.cs b/ZR.Admin.WebApi/Program.cs index b6a1d2f..548b290 100644 --- a/ZR.Admin.WebApi/Program.cs +++ b/ZR.Admin.WebApi/Program.cs @@ -166,12 +166,13 @@ app.UseCors("Policy");//要放在app.UseEndpoints前。 //app.UseHttpsRedirection(); app.UseAuthentication(); +app.UseMiddleware(); app.UseMiddleware(); app.UseAuthorization(); //开启缓存 app.UseResponseCaching(); -if (builder.Environment.IsProduction()||true) +if (builder.Environment.IsProduction() || true) { //恢复/启动任务 app.UseAddTaskSchedulers(); diff --git a/ZR.ServiceCore/Middleware/ExecutionTimeMiddleware.cs b/ZR.ServiceCore/Middleware/ExecutionTimeMiddleware.cs new file mode 100644 index 0000000..4c006d5 --- /dev/null +++ b/ZR.ServiceCore/Middleware/ExecutionTimeMiddleware.cs @@ -0,0 +1,28 @@ +using Microsoft.AspNetCore.Http; + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZR.ServiceCore.Middleware +{ + public class ExecutionTimeMiddleware(RequestDelegate _next) + { + public async Task Invoke(HttpContext context) + { + // 开始计时 + var sw = Stopwatch.StartNew(); + //在将响应标头发送到之前添加要调用的委托客户此处注册的回调按相反顺序运行。 + context.Response.OnStarting(() => + { + sw.Stop(); + context.Response.Headers.TryAdd("X-Request-Duration", $"{sw.Elapsed.TotalMilliseconds} ms"); + return Task.CompletedTask; + }); + await _next(context); + } + } +}