Monthly Archives: September 2012

C# “The server committed a protocol violation. Section=ResponseStatusLine”

This error had me stumped for a few minutes today. When crafting a POST request to an API I found that every other HttpWebRequest during one session would fail throwing the error:

The server committed a protocol violation. Section=ResponseStatusLine

Which was pretty annoying. My tests didn’t pick up the bug earlier as the application only depends on one API function which in the typical use case is called once per session. After checking that all was well with the request and API I headed for Google. Googling the above error turns up a couple of solutions that didn’t work for me.

Solution 1

Add the below to your app.config:

<system.net>
    <settings>
        <httpWebRequest useUnsafeHeaderParsing="true" />
    </settings>
</system.net>

This disables the validation performed on HTTP requests. Although I trust the server providing the API this didn’t really sit right with me.

Solution 2

Set the following property on your request:

request.ServicePoint.Expect100Continue = false;

This again didn’t work for me. Reading the MSDN entry it doesn’t even seem relevant.

What worked

Set the following property on your request:

request.KeepAlive = false;

Issue goes away! When KeepAlive is true keep-alive is sent in the request’s header to the server. This indicates a preference to keep connections alive saving having to tear them down every request.

As I am sending one API request per session my users and the server have little to gain by keeping the connection alive. But I do wonder, this should work magically, so where is the issue arising? The API host is still running IIS6, so perhaps its a legacy thing? Anyway, problem solved for now! I hope this proves useful for someone else.

You can read more about keep-alive and persistant connections over at Wikipedia and more about HttpWebRequest’s KeepAlive property on MSDN.