服务器提交了协议违规。 Section = ResponseHeader Detail = CR必须后跟LF,在WinForms中?

时间:2013-05-26 12:43:30

标签: c# winforms httpwebrequest webclient system.net.webexception

我正在尝试使用WebClient / HttpWebRequest从服务器下载一些数据。我使用以下代码来执行此操作:

WebClient client = new WebClient();
client.Credentials = new NetworkCredential("admin", "password");
Stream datastream = client.OpenRead("http://routerlogin.com/cgi-bin/CF_logs.html");
StreamReader reader = new StreamReader(datastream);

服务器是我的页面在路由器的配置中。它在浏览器中工作正常,但是当使用我的代码下载时,它会抛出WebException消息

  

服务器提交了协议违规。 Section = ResponseHeader Detail = CR必须后跟LF,在WinForms?中。

我找到了一个解决方案,如果他们使用ASP.net就会使用,将以下内容添加到web.config中:

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

但是,我正在制作一个WinForms应用程序,所以这对我不起作用。有什么替代方法可以解决这个问题?

2 个答案:

答案 0 :(得分:24)

首先,添加app.config文件就像添加任何其他文件一样简单How to: Add an Application Configuration File to a C# Project

然后,您只需将上面的代码段添加到新的app.config。

另一种通过代码设置该属性的方法,显示herehere,无法显示app.config。

答案 1 :(得分:2)

您的问题可能不需要任何app.config更改(就我而言,此配置更改没有影响)。我会尝试按照建议的in this link修改您的Accept:标头。

就我而言,我直接创建了一个HttpWebRequest,因此我的解决方案是添加以下内容:

request.Accept = "text/html, application/xhtml+xml, */*"