title: Headers are read only exception when writing to HttpResponse
body: <p>I have a controller that looks like this</p>
  
  <pre><code>IHttpWrite httpWrite;
  
  [HttpPost]
  public async Task&lt;HttpResponse&gt; Post(Request req)
  {
      return await httpWrite.Write(req, Response);
  }
  </code></pre>
  
  <p>that calls this</p>
  
  <pre><code>public async Task&lt;HttpResponse&gt; Write(object data, HttpResponse httpResponse)
  {
      var json = JsonConvert.SerializeObject(data);
  
      httpResponse.OnStarting(() =&gt;
      {
          httpResponse.Clear();
          httpResponse.ContentType = "application/json";
          return Task.CompletedTask;
      });
  
      await httpResponse.WriteAsync(json);
      return httpResponse;
  }
  </code></pre>
  
  <p>But calling it gets this exception</p>
  
  <pre><code>System.InvalidOperationException: Headers are read-only, response has already started.
     at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpHeaders.ThrowHeadersReadOnlyException()
  </code></pre>
  
  <p>I understand you cannot set the headers once data is written to the response, but on my end I am setting the headers in the HttpResponse before writing anything to it.</p>
  
  <p>From the debugging I've done, the exception for the headers is only being thrown after the controller returns the HttpResponse. This indicates to me the attempt to change the headers is being done on something outside of my code. </p>
  
  <p>I'm using most of the boilerplate code Visual Studio sets up. This is the default Program</p>
  
  <pre><code>public static IWebHostBuilder CreateWebHostBuilder(string[] args) =&gt;
          WebHost.CreateDefaultBuilder(args)
                 .UseStartup&lt;Startup&gt;();
  </code></pre>
  
  <p>Which is calling the mostly-default Startup</p>
  
  <pre><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
      if (env.IsDevelopment())
      {
          app.UseDeveloperExceptionPage();
      }
      else
      {
          app.UseHsts();
      }
  
      app.UseHttpsRedirection();
      app.UseStaticFiles();
      app.UseMvc();
  }
  </code></pre>
  
  <p>I believe the solution either lies in changing something in the configuration to not automatically set the response headers after I return the HttpResponse, or potentially returning a different object instead so that I do not have to manually set the headers. Without being able to know the source of what's trying to set the headers after I write to the HttpResponse, I am unsure how to proceed.</p>