The server committed a protocol violation. Section=ResponseStatusLine
Switching off header validation in .NET
Recently I was adding GitHub project section to my blog when I run into the following exception "The server committed a protocol violation. Section=ResponseStatusLine"
After some time of Google-ing I found few solutions, but the most simplest one was actually the best one. Apparently, I needed to switch off request header parsing.
<system.net> <settings> <httpWebRequest useUnsafeHeaderParsing = "true"/> </settings> </system.net>
This worked for my problem when pulling GitHub API JSON feed, but I wanted to dig in and figure out what is this setting really doing (except solving my problem out of the box).
I checked Microsoft's online documentation on MSDN and it turns out that HttpWebRequest and HttpWebResponse are doing a bunch of stuff aside from pulling the content on demand.
I went one step further and tried to achieve this switching off from the code. However this value will be used in a request directly from config, so it is not accessible on the request instance level.
After some time Google-ing, I found a method which is doing this with reflection on .NET configuration class instance.
public static bool SetAllowUnsafeHeaderParsing(bool value) { //Get the assembly that contains the internal class Assembly aNetAssembly = Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection)); if (aNetAssembly != null) { //Use the assembly in order to get the internal type for the internal class Type aSettingsType = aNetAssembly.GetType("System.Net.Configuration.SettingsSectionInternal"); if (aSettingsType != null) { //Use the internal static property to get an instance of the internal settings class. //If the static instance isn't created allready the property will create it for us. object anInstance = aSettingsType.InvokeMember("Section", BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { }); if (anInstance != null) { //Locate the private bool field that tells the framework is unsafe header parsing should be allowed or not FieldInfo aUseUnsafeHeaderParsing = aSettingsType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance); if (aUseUnsafeHeaderParsing != null) { aUseUnsafeHeaderParsing.SetValue(anInstance, value); return true; } } } } return false; }
Original code URL is listed in the references list.
References
- http://msdn.microsoft.com/en-us/library/system.net.configuration.httpwebrequestelement.useunsafeheaderparsing(v=vs.110).aspx
- https://social.msdn.microsoft.com/Forums/en-US/ff098248-551c-4da9-8ba5-358a9f8ccc57/how-do-i-enable-useunsafeheaderparsing-from-code-net-20?forum=netfxnetcom
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
Comments for this article