服务器提交了协议冲突. Section=ResponseHeader Detail=CR 后面必须是 LF

以下是引发问题的代码:

 

网上查了一下,发现都是这样:

解决方案:winfrom 在app.config种添加 web 在 web.config种添加

 <system.net>
    <settings>
      <httpWebRequest useUnsafeHeaderParsing="true" />
    </settings>
  </system.net>
或者以反射的形式在程序中设定useUnsafeHeaderParsing的值【该方法须在发送请求之前进行设定否则无效果】
ToggleAllowUnsafeHeaderParsing(true);
public static bool ToggleAllowUnsafeHeaderParsing(bool enable)
        {
            Assembly assembly = Assembly.GetAssembly(typeof(SettingsSection));
            if (assembly != null)
            {
                Type settingsSectionType = assembly.GetType("System.Net.Configuration.SettingsSectionInternal");
                if (settingsSectionType != null)
                {
                    
                    object anInstance = settingsSectionType.InvokeMember("Section",
                    BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { });
                    if (anInstance != null)
                    {
                        FieldInfo aUseUnsafeHeaderParsing = settingsSectionType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance);
                        if (aUseUnsafeHeaderParsing != null)
                        {
                            aUseUnsafeHeaderParsing.SetValue(anInstance, enable);
                            return true;
                        }

                    }
                }
            }
            return false;
        }

  以上代码引用自:https://www.cnblogs.com/aochulai/p/3881415.html,并且添加了 ToggleAllowUnsafeHeaderParsing(true); 后果然OK了。

 

但问题所在是在哪里呢,所谓前人栽树,后人乘凉。从https://www.cnblogs.com/lewisli/p/6775010.html得出该问题的查找方法。

其实“服务器提交了协议冲突. Section=ResponseHeader Detail=CR 后面必须是 LF” 这个问题的原因主要是以下几点导致的:

  

从百度得知:

在文本处理中, CR, LF, CR/LF是不同操作系统上使用的换行符.

Dos和windows采用回车+换行CR/LF表示下一行,

而UNIX/Linux采用换行符LF表示下一行,

CR等于回车(\r),LF等于换行(\n)

在HTTP协议中HTTP Header请求信息中的每一行都必须是在CRLF来结束。

服务器检测到你提交的请求不符合HTTP协议的这个规定,所以拒绝了你的请求。

 

那么究竟是哪一个部分产生出了不符合HTTP协议的格式的信息,是在http header的请求(Request)部分,还是响应信息(Response)部分呢?

是我提交的header的格式没有按照“CRLF结尾”的规定,还是服务器根据我提交的heaer所产生的响应header没有按照“CRLF结尾”的规定?

 

于是我打开WireShark,监测要连接的IP。

以下是POST的信息:

 

 

以下是返回的信息:

 

最终得出,服务端返回的信息头里边的Content-Type没有以\r\n结尾。

  

参考文章:

https://www.cnblogs.com/lewisli/p/6775010.html

https://docs.microsoft.com/zh-cn/dotnet/api/system.net.configuration.httpwebrequestelement.useunsafeheaderparsing?redirectedfrom=MSDN&view=netframework-4.8#System_Net_Configuration_HttpWebRequestElement_UseUnsafeHeaderParsing

http://www.360doc.com/content/11/0113/20/3508740_86319358.shtml

https://my.oschina.net/EricWe/blog/126844

http://www.360doc.com/content/10/0930/17/3668821_57590979.shtml

https://www.cnblogs.com/aochulai/p/3881415.html

posted @ 2020-07-27 17:56  努力吧兄Dei  阅读(2904)  评论(0编辑  收藏  举报