title: Setting the Content-Type of an empty response in ASP.NET MVC
body: <p>In order to support a legacy application that's in the field, I need my ASP.NET MVC app to return an empty response that also has a <code>Content-Type</code>. One of IIS, ASP.NET, or ASP.NET MVC is removing my <code>Content-Type</code> when I send back a null response. Is there any way around this?</p>
  
  <p>(While not requiring an empty response with a set <code>Content-Type</code> would obviously be the ideal solution, the clients are already out there, and many of them cannot be upgraded.)</p>
  
  <p><strong>EDIT</strong>: Since there was a request for code: I'm proxying the request from the new web application to the one that older clients rely on. To do this, I have a subclass of <code>ActionResult</code>, called <code>LegacyResult</code>, that you can simply return for those methods that need to be handled by the old software. This is the relevant part of its code:</p>
  
  <pre><code>    public override void ExecuteResult(ControllerContext context)
      {
          using (var legacyResponse = GetLegacyResponse(context))
          {
              var clientResponse = context.HttpContext.Response;
              clientResponse.Buffer = false;
              clientResponse.ContentType = legacyResponse.ContentType; /* Yes, I checked that legacyResponse.ContentType is never string.IsNullOrEmpty */
              if (legacyResponse.ContentLength &gt;= 0) clientResponse.AddHeader("Content-Length", legacyResponse.ContentLength.ToString());
  
              var legacyInput = legacyResponse.GetResponseStream();
              using (var clientOutput = clientResponse.OutputStream)
              {
                  var rgb = new byte[32768];
                  int cb;
                  while ((cb = legacyInput.Read(rgb, 0, rgb.Length)) &gt; 0)
                  {
                      clientOutput.Write(rgb, 0, cb);
                  }
                  clientOutput.Flush();
              }
          }
      }
  </code></pre>
  
  <p>If <code>legacyInput</code> has data, then <code>Content-Type</code> is set appropriately. Otherwise, it's not. I can actually kluge the old backend to send an empty v. non-empty response for exactly the same request, and observe the difference in Fiddler.</p>
  
  <p><strong>EDIT 2</strong>: Poking around with Reflector reveals that, if headers have not been written at the time that <code>HttpResponse.Flush</code> is called, then <code>Flush</code> writes out the headers itself. The problem is that it only writes out a tiny subset of the headers. One of the missing ones is <code>Content-Type</code>. So it seems that, if I can force headers out to the stream, I can avoid this problem.</p>