Add Response Headers to ASP.NET Core Middleware
<p>I want to add a processing time middleware to my ASP.NET Core WebApi like this</p>

<pre><code>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() });
    }
}
</code></pre>

<p>But doing this throws an exception saying</p>

<pre><code> System.InvalidOperationException: Headers are readonly, reponse has already started.
</code></pre>

<p>How can I add headers to the response?</p>