How to set useUnsafeHeaderParsing in code

Barka picture Barka · Dec 8, 2011 · Viewed 34.8k times · Source

I am getting the following exception:

The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF

From this question:

HttpWebRequestError: The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF

I understand that I need to set useUnsafeHeaderParsing to True.

Here is my code:

HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
WebResponse myResp = myReq.GetResponse(); //exception is thrown here

useUnsafeHeaderParsing is a property of HttpWebRequestElement class.

How do I integrate it in the above code?

Answer

Edwin de Koning picture Edwin de Koning · Dec 12, 2011

You need to set this is in your web.config, inside <system.net> section, like this:

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

If, for some reason, you do not want to do it from your config, you could do it from code by prgrammatically setting your config settings. See this page for an example.