Semen Shekhovtsov
Semen Shekhovtsov

Reputation: 882

ContentType HTTP header is missing in Server response

I have a ASP.NET MVC web action which returns a simple zip file. The Responce.ContentType property is manually set to "text/xml; charset=utf-8; gzip". This header value is set before writing response content to the output stream. Web project is hosted on Windows Azure hosting. The problem is that sometimes server returns response with missing ContentType header field, this causes issues on the client side. Having no idea what could be the reason of it. When I run same web project locally - everything works fine, ContentType field has proper value. Sample web action code:

public void GetData()
{
            Response.ContentType = "text/xml; charset=utf-8; gzip";
            XDocument xml = new XDocument(...);//some large XML file
            byte[] byteData = Encoding.UTF8.GetBytes(xml.ToString());
            Stream outputStream = Response.OutputStream;
            GZipStream compressedzipStream = new GZipStream(outputStream, CompressionMode.Compress);
            compressedzipStream.Write(byteData, 0, byteData.Length);
            compressedzipStream.Close();
}

Any help would be much appreciated.

Upvotes: 1

Views: 6595

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could write a custom action result:

public class CompressedXDocumentResult : FileResult
{
    private readonly XDocument _xdoc;
    public CompressedXDocumentResult(XDocument xdoc)
        : base("text/xml; charset=utf-8; gzip")
    {
        _xdoc = xdoc;
    }

    protected override void WriteFile(HttpResponseBase response)
    {
        using (var gzip = new GZipStream(response.OutputStream, CompressionMode.Compress))
        {
            var buffer = Encoding.UTF8.GetBytes(_xdoc.ToString());
            gzip.Write(buffer, 0, buffer.Length);
        }
    }
}

and then:

public ActionResult GetData()
{
    XDocument xml = ...
    return new CompressedXDocumentResult(xml);
}

Also note that text/xml; charset=utf-8; gzip is not a standard HTTP Content-Type header. So unless you write some custom client that will understand it, it is unlikely that any standard browser will be able to parse it.

If you wanted to indicate that the response is compressed you'd better use the Content-Encoding header. You could either activate compression for dynamic contents directly at IIS level and don't bother in your code or if you don't have access to IIS you could simply write a custom action filter:

[OutputCompress]
public ActionResult GetData()
{
    XDocument xml = ...
    byte[] buffer = Encoding.UTF8.GetBytes(xml.ToString());
    return File(buffer, "text/xml; charset=utf-8");
}

Upvotes: 1

Sean
Sean

Reputation: 1822

try this:

Response.Clear();    
Response.ContentType = "text/xml; charset=utf-8; gzip";

Upvotes: 0

Related Questions