I create a middleware to stop every request in my WebAPI, but i want to set the Response Time in the Headers.
Example without the middleware:
[HttpGet]
public IActionResult Index()
{
var watcher = Stopwatch.StartNew();
watcher.Stop();
HttpContext.Response.Headers.Add("x-response-time", watcher.ElapsedMilliseconds.ToString());
return Ok(new { message = "Success" });
}
Then I create the middleware:
public async Task Invoke(HttpContext httpContext)
{
Stopwatch watch = new Stopwatch();
watch.Start();
await _next(httpContext);
watch.Stop();
httpContext.Request.Headers.Add("x-time", watch.ElapsedMilliseconds.ToString());
}
But the result is not the expect, because i can't change the context after the calling to the _next.