System.Net.WebException: 服务器违反了协议

System.Net.WebException: The server committed a protocol violation

我有以下代码可以依次调用 returns xml:

private string Send(string url)
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (Stream stream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
    catch (WebException ex)
    {
        var _status = ex.Status.ToString();
        if (ex.Status == WebExceptionStatus.ProtocolError)
        {
            _status = ((HttpWebResponse)ex.Response).StatusCode.ToString();
        }
        Trace.WriteLine(_status.ToString());
    }

    return "error";
}

大多数时候(不总是)我得到

System.Net.WebException: The server committed a protocol violation.

Section=ResponseStatusLine at System.Net.HttpWebRequest.GetResponse()

抛出异常。

我已将其直接添加到 App.config 的 <configuration> 部分:

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

但我仍然遇到错误。

设置

request.KeepAlive = false;

http://www.webmonkeys.org.uk/2012/09/c-the-server-committed-a-protocol-violation-sectionresponsestatusline/#comment-60

此外,您粘贴的 useUnsafeHeaderParsing 配置值已设置为 false,如果您试图解决此问题,则应将其设置为 true。

request.ServicePoint.Expect100Continue = true;