C#:处理WebClient"协议违规"

Kal*_*lEl 16 c#

我需要在路由器中读取一个位置,但是我得到以下异常 -

ServerProtocolViolation "The server committed a protocol violation. 
                        Section=ResponseHeader Detail=CR must be followed by LF"
Run Code Online (Sandbox Code Playgroud)

当我使用该.DownloadString(url)功能时会发生这种情况.有没有办法让WebClient忽略协议违规?在谷歌搜索告诉我,我应该在useUnsafeHeaderParsing某处设置选项.我可以通过程序来完成吗?如果我使用它会有什么影响?

编辑:附加代码 -

    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());
        }
    }
Run Code Online (Sandbox Code Playgroud)

Lum*_*mmo 24

看起来最简单的方法是在您的应用中包含.config文件,其中包含以下内容:

<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing = "true"/>
</settings>
</system.net>
Run Code Online (Sandbox Code Playgroud)

然而,它也可以在代码中执行,但它似乎有点凌乱:

http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/ff098248-551c-4da9-8ba5-358a9f8ccc57

另请注意,该属性的MSDN定义是

设置此属性会忽略HTTP解析期间发生的验证错误.

http://msdn.microsoft.com/en-us/library/system.net.configuration.httpwebrequestelement.useunsafeheaderparsing.aspx

所以我说它使用起来相当安全,尽管它确实只提到它是为了向后兼容.

  • 谢谢,虽然你说的很乱,但它有效.这应该像在WebClient类中设置属性一样简单.微软(几乎)硬编码遵守RFC的决定是非常值得怀疑的 - 它应该对程序员开放.这几乎看起来像一个短路 - 认为程序员总是有权修复服务器端协议违规. (6认同)