The server committed a protocol violation

I’m currently working on a C#/.net project. Early on we found the following error kept appearing. The server committed a protocol violation. Section=ResponseHeader.

Numerous Google searches all returned the same piece of advice: add the useUnsafeHeaderParsing flag to the config file. Although this seemed to resolve the error, now that we’ve started to get serious usage we’ve noticed the error still appears every now and then in the logs.

The root of this problem appears to be related to security measures implemented in the HttpWebRequest class. A good solution we’ve found is to use a TCP client instead as this completely bypasses any checks of the HTTP headers.

Here’s the code:

string response = string.Empty;

Uri uri = new Uri("http://www.domain.com:80/script");
TcpClient tcpClient = new TcpClient(uri.Host, uri.Port);            

using (NetworkStream networkStream = tcpClient.GetStream())
{
	StreamWriter streamWriter = new StreamWriter(networkStream);
	StreamReader streamReader = new StreamReader(networkStream);

	streamWriter.WriteLine(string.Format("POST {0} HTTP/1.0", uri.AbsolutePath));
	streamWriter.WriteLine(string.Format("Host: {0}", uri.Host));
	streamWriter.WriteLine(string.Format("Content-Length: {0}", data.Length));
	streamWriter.WriteLine("");
	streamWriter.WriteLine(data);
	streamWriter.Flush();

	var isBody = false;
	while (streamReader.Peek() >= 0)
	{
		var line = streamReader.ReadLine().Trim();
                    
		if (line == string.Empty)
		{
			isBody = true;
		}
		else if (isBody)
		{
			response += line;
		}                    
	}
                
	streamReader.Close();
	streamWriter.Close();
}

tcpClient.Close();