我想向我的ASP.NET Core WebApi添加一个处理时间中间件,就像这样:
public class ProcessingTimeMiddleware
{
private readonly RequestDelegate _next;
public ProcessingTimeMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var watch = new Stopwatch();
watch.Start();
await _next(context);
context.Response.Headers.Add("X-Processing-Time-Milliseconds", new[] { watch.ElapsedMilliseconds.ToString() });
}
}
但这样做会抛出一个异常,提示
System.InvalidOperationException: Headers are readonly, reponse has already started.
我该如何向响应中添加头信息?
await _next(context)
应该是最后一个语句(在context.Response.Headers.Add
之后)。这样更符合语义。 - Roman Pokrovskij