Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

c# - IIS & Chrome: failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING

I recently came across a Chrome issue which I think is worth sharing it with you.

I worked on a self written API using an HttpHandler which primary should return json data. But when an error occures I wanted to display an html file. That worked pretty well in IE and FF, but not in Chrome.

Looking to the developer tools revealed this error: net::ERR_INCOMPLETE_CHUNKED_ENCODING

Google said not very much about this issue while it was seen very much. All I got to know was, that it was magically disappearing after some time.

I found out it lays on this lines of code:

result.StoreResult(context);
context.Response.Flush();
context.Response.Close(); //<-- this causes the error

After removing the last line it worked well. I don′t know why only Chrome had/has an issue with that, but it seemed as if I closed the response stream before chrome finished reading it.

I hope it helps those of you coming across the same or a similar issue.

Now my question: How is the best pratice in closing/flushing the response stream? Are there any rules?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to ASP.NET sets the transfer encoding as chunked on premature flushing the Response:

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.

Solution: 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:

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());

    response.BinaryWrite(b);
    try
    {
        this.Context.Response.Flush();
        this.Context.Response.Close();
    }
    catch (Exception) { }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...