HttpWebRequestElement.UseUnsafeHeaderParsing Property
异常信息
System.Net.WebException:“服务器提交了协议冲突. Section=ResponseHeader Detail=CR 后面必须是 LF”
解决办法
一、通过配置文件实现
web.config或app.config中设置如下属性
<system.net> <settings> <httpWebRequest useUnsafeHeaderParsing="true" /> </settings> </system.net>
二、通过代码实现
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Configuration; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace UnsafeHeaderParsingSample { internal class Program { private static void Main() { // Enable UseUnsafeHeaderParsing if (!ToggleAllowUnsafeHeaderParsing(true)) { // Couldn't set flag. Log the fact, throw an exception or whatever. } // This request will now allow unsafe header parsing, i.e. GetResponse won't throw an exception. var request = (HttpWebRequest)WebRequest.Create("http://localhost:8000"); var response = request.GetResponse(); // Disable UseUnsafeHeaderParsing if (!ToggleAllowUnsafeHeaderParsing(false)) { // Couldn't change flag. Log the fact, throw an exception or whatever. } // This request won't allow unsafe header parsing, i.e. GetResponse will throw an exception. var strictHeaderRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8000"); var strictResponse = strictHeaderRequest.GetResponse(); } // Enable/disable useUnsafeHeaderParsing. // See http://o2platform.wordpress.com/2010/10/20/dealing-with-the-server-committed-a-protocol-violation-sectionresponsestatusline/ public static bool ToggleAllowUnsafeHeaderParsing(bool enable) { //Get the assembly that contains the internal class Assembly assembly = Assembly.GetAssembly(typeof(SettingsSection)); if (assembly != null) { //Use the assembly in order to get the internal type for the internal class Type settingsSectionType = assembly.GetType("System.Net.Configuration.SettingsSectionInternal"); if (settingsSectionType != null) { //Use the internal static property to get an instance of the internal settings class. //If the static instance isn't created already invoking the property will create it for us. object anInstance = settingsSectionType.InvokeMember("Section", BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { }); if (anInstance != null) { //Locate the private bool field that tells the framework if unsafe header parsing is allowed FieldInfo aUseUnsafeHeaderParsing = settingsSectionType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance); if (aUseUnsafeHeaderParsing != null) { aUseUnsafeHeaderParsing.SetValue(anInstance, enable); return true; } } } } return false; } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)