public class RequestTimingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestTimingMiddleware> _logger;
public RequestTimingMiddleware(RequestDelegate next, ILogger<RequestTimingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var stopwatch = Stopwatch.StartNew();
await _next(context);
stopwatch.Stop();
var elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
_logger.LogInformation("Request {HttpMethod} {Path} finished in {ElapsedMilliseconds}ms",
context.Request.Method, context.Request.Path, elapsedMilliseconds);
// 这里可以添加逻辑来根据请求内容长度和处理时间计算接收速率
// 但由于Kestrel内部处理速率,直接计算可能不准确
}
}
// 在Startup.cs的Configure方法中使用中间件
public void Configure(IApplicationBuilder app)
{
// ... 其他中间件配置 ...
app.UseMiddleware<RequestTimingMiddleware>();
// ... 其他中间件配置 ...
app.UseEndpoints(endpoints =>
{
// ... 配置你的路由 ...
});
}
03-03
328
03-24
467
03-05
1192
01-26
1393