c# - System.Net.WebException:服务器违反了协议(protocol)

标签 c# system.net.webexception

我有以下代码来进行调用,然后返回 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。

关于c# - System.Net.WebException:服务器违反了协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39919955/

相关文章:

c# - 在.NET Core 3.+ 中的startup.cs ConfigureServices 或program.cs Main 方法中注册IHostedService 是否有区别?

c# - 将 DLL 导入 Unity - 找不到类型或命名空间

c# - 从控制台中删除特殊字符以加载 txt 文件

c# - 用 XElement 替换 XElement 内容

c# - 中止请求 wp7

C# - WebClient - 远程服务器发送 503 错误

c# - 使用 Microsoft 的 Visual UI Automation 验证

System.Net.WebException 的 Powershell 处理

c# - 如果我正在使用的 Web 服务超时,会抛出什么异常?

c# - 无法从 WebException 获取 ResponseStream