我想像这样向我的 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.
如何向响应添加 header ?
最佳答案
没关系,代码在这里
public async Task Invoke(HttpContext context)
{
var watch = new Stopwatch();
watch.Start();
//To add Headers AFTER everything you need to do this
context.Response.OnStarting(state => {
var httpContext = (HttpContext)state;
httpContext.Response.Headers.Add("X-Response-Time-Milliseconds", new[] { watch.ElapsedMilliseconds.ToString() });
return Task.CompletedTask;
}, context);
await _next(context);
}
关于c# - 将响应 header 添加到 ASP.NET Core 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37395227/