C# – System.Net.WebException: The server committed a protocol violation

csystem.net.webexception

I have the following code to make a call that in turn returns xml:

private string Send(string url)
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (Stream stream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
    catch (WebException ex)
    {
        var _status = ex.Status.ToString();
        if (ex.Status == WebExceptionStatus.ProtocolError)
        {
            _status = ((HttpWebResponse)ex.Response).StatusCode.ToString();
        }
        Trace.WriteLine(_status.ToString());
    }

    return "error";
}

Most of the time (not always) I get

System.Net.WebException: The server committed a protocol violation.

Section=ResponseStatusLine at System.Net.HttpWebRequest.GetResponse()

exception thrown.

I have added this to my App.config directly in the <configuration> section:

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

But I continue to get the error.

Best Answer

Set

request.KeepAlive = false;

http://www.webmonkeys.org.uk/2012/09/c-the-server-committed-a-protocol-violation-sectionresponsestatusline/#comment-60

Also, the useUnsafeHeaderParsing config value that you pasted has it set as false, when you should be setting it to true, if you're attempting to get past this issue.