I want to add a processing time middleware to my ASP.NET Core WebApi like this
public class ProcessingTimeMiddleware
{
private readonly RequestDelegate
In your example headers already sent, when execution reaches context.Response.Headers.Add(...) statement.
You can try:
public async Task Invoke(HttpContext context)
{
var watch = new Stopwatch();
context.Response.OnSendingHeaders(x =>
{
watch.Stop();
context.Response.Headers.Add("X-Processing-Time-Milliseconds", new[] { watch.ElapsedMilliseconds.ToString() });
}, null);
watch.Start();
await _next(context);
watch.Stop();
}