Well, I discovered this problem and its solution sometime earlier. However lately, a couple of my colleagues approached me for advice with the same issue, and I thought of writing a blog post for the same.

In a nut-shell, the problem is that ASP.NET transfers the data to the client in chunked encoding (Transfer-Encoding: chunked), if you prematurely flush the Response stream for the Http request and the Content-Length header for the Response is not explicitly set by you.

Normally this should not be a problem because most modern HTTP clients are capable of handling both chunked as well as non-chunked server responses, de-chunking the chunked response automatically (Note that Chunked transfer encoding is defined only by HTTP 1.1 specification).

However, in my own case, I was making an asynchronous Ajax call to an ASP.NET web-service from javascript. And the web-method handling the request flushed the Response explicitly to the client, and then closed the Response (I needed to do so, because the request was issued from an auto-load call of an ExtJs store, and I needed to close the connection on the server for the client-side Store to accept and load the json serialized data).

As it turned out, the browser did not automatically de-chunked the chunked server response received as a result of an XmlHttpRequest. When I first analyzed the chunked response through Fiddler, I was surprised to see random characters (e.g. 1f7) in the server response, which I later realized were actually part of the chunk delimiter string.

A frantic Google search on why the response was chunked threw up a helpful question on StackOverflow, which gave me the insight of the above ASP.NET behavior regarding sending chunked responses on premature flushing.

And the solution was comparatively simple: You need to explicitly set the Content-Length header for the Response to prevent ASP.NET from chunking the response on flushing.

Here’s the C# code that I used for preventing ASP.NET from chunking the response by setting the required header:


{syntaxhighlighter brush: csharp;fontsize: 100; first-line: 1; }protected void writeJsonData (string s)
HttpContext context=this.Context;
HttpResponse response=context.Response;

context.Response.ContentType = “text/json”;

byte[] b = response.ContentEncoding.GetBytes(s);
response.AddHeader(“Content-Length”, b.Length.ToString());

catch (Exception) { }