live-forum/server/webapi/LiveForum/LiveForum.Code/MiddlewareExtend/ExecutionTimeMiddleware.cs
2026-03-24 11:27:37 +08:00

34 lines
977 B
C#

using Microsoft.AspNetCore.Http;
using System.Diagnostics;
namespace LiveForum.Code.MiddlewareExtend
{
/// <summary>
/// 方法执行时间
/// </summary>
public class ExecutionTimeMiddleware(RequestDelegate _next)
{
public async Task Invoke(HttpContext context)
{
// 开始计时
var sw = Stopwatch.StartNew();
//在将响应标头发送到之前添加要调用的委托客户此处注册的回调按相反顺序运行。
if (!context.Response.HasStarted)
{
context.Response.OnStarting(() =>
{
sw.Stop();
context.Response.Headers.TryAdd("X-Request-Duration", $"{sw.Elapsed.TotalMilliseconds} ms");
return Task.CompletedTask;
});
}
else
{
sw.Stop();
}
await _next(context);
}
}
}