C#:处理 WebClient "protocol violation"

标签 c#

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

ServerProtocolViolation "The server committed a protocol violation. 
                        Section=ResponseHeader Detail=CR must be followed by LF"

当我使用 .DownloadString(url) 函数时会发生这种情况。有没有办法让 WebClient 忽略协议(protocol)违规? Google 中的搜索告诉我应该在某处设置 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());
        }
    }

最佳答案

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

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

不过也可以在代码中完成,但看起来有点乱:

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

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

Setting this property ignores validation errors that occur during HTTP parsing.

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

所以我会说它使用起来相当安全,尽管它确实提到仅将其用于向后兼容。

关于C#:处理 WebClient "protocol violation",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3142403/

相关文章:

c# - 如何防止重复项目listView C#

c# - 使 UDP 成为面向连接的协议(protocol)?

c# - 在 C# 中获取当前获得焦点的文本框

c# - wcf 将列表作为方法参数传递

c# - 如何使用填充数组的类型对象的属性序列化类

c# - MEF 插件依赖项未加载,因为未检查插件目录

c# - 将 ViewModel 绑定(bind)到多个窗口

c# - 更新已使用自定义属性扩展的 AD UserPrincipal

c# - 在等待在同一线程上执行后如何获得继续?

c# - 用于处理个人和经常性费用的数据库设计