C#:处理WebClient“违反协议” [英] C#: Handling WebClient "protocol violation"
问题描述
我需要读取路由器中的一个位置,但是出现以下异常-
I need to read a location in my Router, but I get the following exception -
ServerProtocolViolation "The server committed a protocol violation.
Section=ResponseHeader Detail=CR must be followed by LF"
当我使用 .DownloadString(url)
函数时。有什么方法可以使 WebClient
忽略协议违规? Google中的搜索告诉我,应该在某处设置 useUnsafeHeaderParsing
选项。我可以通过程序吗?
This occurs when I use the .DownloadString(url)
function. Is there any way to make WebClient
ignore protocol violation? Searches in Google tell me I should set the useUnsafeHeaderParsing
option somewhere. Can I do it through program? What's the catch if I use it?
编辑:附加代码-
public Readlog() {
WebClient wc = new WebClient();
string url = @"http://192.168.0.1/setup.cgi?next_file=log.htm&todo=cfg_init";
Console.WriteLine(url);
try {
//wc.Headers.Add("User-Agent", "Mozilla/5.0(Windows; U; Windows NT 5.2; rv:1.9.2) Gecko/20100101 Firefox/3.6");
wc.Credentials = new NetworkCredential("admin", "admin");
//Next line causes exception System.Net.WebException
//Message - "The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF"
//May be I need to use useUnsafeHeaderParsing somehow to avoid that
string result = wc.DownloadString(url);
Console.WriteLine(result);
} catch (WebException we) {
System.Diagnostics.Trace.WriteLine(we.ToString());
}
}
推荐答案
外观例如,最简单的方法是在应用程序中包含一个.config文件,其中包含以下内容:
Looks like the easiest way is including a .config file with your app containing the following:
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing = "true"/>
</settings>
</system.net>
但是也可以在代码中完成,但这似乎有些混乱:
However it's also possible to do it within the code but it seems a little messy:
还要注意,该属性的MSDN定义是
Also note that the MSDN definition of that property is
设置此属性会忽略
期间发生的$$验证错误b $ b HTTP解析。
Setting this property ignores validation errors that occur during HTTP parsing.
所以我说它相当安全,尽管它确实提到只为了向后兼容才使用它。
So I'd say it's fairly safe to use, although it does mention to only use it for backwards compatibility.
这篇关于C#:处理WebClient“违反协议”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!