title: Adding Response Headers with Custom Middleware Asp.Net-Core
body: <p>I have 3 microservices and try to create correlation id to keep track of the every log issues. If corrID is not null when request comes, then I set it. If not, it is generated. And then passed to the next. I want to see  corrId for 3 services' logs. If I used the code below everything works well. But swagger does not work. </p>
  
  <p>Exception: headers are read-only response has already started. </p>
  
  <pre><code> public async Task Invoke(HttpContext context)
              {
                  string key = context.Request.Headers.Keys.FirstOrDefault(n =&gt; n.Equals("Correlation-ID"));
  
                  var corrID = context.RequestServices.GetService&lt;CorrelationID_Global&gt;();
  
                  if (corrID != null)
                  {
                      if (!string.IsNullOrWhiteSpace(key))
                      {
  
                          corrID.ID = context.Request.Headers[key].ToString();
                      }
                      else
                      {
                          corrID.ID = Guid.NewGuid().ToString();
  
                      }
                  }
  
                  await _next(context);
  
                  if (!string.IsNullOrWhiteSpace(corrID?.ID))
                  {               
                          context.Response.Headers.Add("Correlation-ID", corrID.ID);
                  }
  
              }
  </code></pre>
  
  <p>To solve swagger problem,  I change the last if statement using this link: <a href="https://stackoverflow.com/questions/37395227/add-response-headers-to-asp-net-core-middleware">Add Response Headers to ASP.NET Core Middleware</a> </p>
  
  <pre><code>  if (!string.IsNullOrWhiteSpace(corrID?.ID))
      {
          context.Response.OnStarting((state) =&gt;
          {
              context.Response.Headers.Add("Correlation-ID", corrID.ID);
              return Task.FromResult(0);
          },null);
      }
  </code></pre>
  
  <p>However, this time I cannot see correlation-Id at responses' log of services.Thus corrID of requests' log changes as usual. How can I handle this problem? Thanks.  </p>