HttpWebRequest某些Web服务器的Url时出现错误

出错现象

使用.Net Framework中的HttpWebRequest下载某些Web服务器的Url的时候,对于一般浏览器可以下载的某些网页,会出现下面的错误信息。

The underlying connection was closed: The server committed an HTTP protocol violation.

根据微软的解释,这是因为这些Web浏览器没有遵循HTTP 1.1 RFC中对于Response的规范,在Response的Header部分中出现了非法字符。不过,即使是IE浏览器,也是可以浏览这些网页的。

绕开方法

在可执行文件所在的那个项目文件中,增加app.config文件,也就是Application Configuration File,然后在configuration这个Tag中加入下面的Xml代码。

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

如果希望所有.Net程序都没有这个问题,可以把这段代码也加在Machine.Config中,这个文件在下面这个目录里面。如果针对Asp.net,可以加入到Web.Config中,也是在下面这个目录里面。

%SystemRoot%\Microsoft.NET\Framework\versionNumber\CONFIG\

网上有个帖子说,这种绕开方法实际上是存在这安全风险的,微软应该在.Net中彻底解决这个问题,而不是让用户使用这样一个有安全风险的绕开方法。

通过程序代码绕开

在MSDN论坛中有一个帖子,How do I enable useUnsafeHeaderParsing from code? (.NET 2.0),讨论如何不修改app.config或者Machine.Config文件,而在代码中通过程序来设置useUnsafeHeaderParsing属性,代码如下。

public static bool SetAllowUnsafeHeaderParsing20()
{
//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, true);
return true;
}
}
}
}
return false;
}

参考文献

作者: 杰棍 [Jegwon]

波波坡原创文章 链接:http://www.bobopo.com/article/code/httpwebrequest_protocol_violation.htm

标签:

关键词: HttpWebRequest, 错误, useUnsafeHeaderParsing, app.config, VB.Net, .Net Framework, DotNet

创建日期: 2008-01-06

文库 微博 博客 作品 首页