【问题标题】:C# WebClient Exception: The underlying connection was closedC# WebClient 异常:底层连接已关闭
【发布时间】:2017-11-02 14:42:55
【问题描述】:

我正在向 UPS 网站发送 xml 数据,有时我收到响应,有时我收到 异常:底层连接已关闭

查看将 xml 发送到特定 UPS url 的示例代码。

    public ShippingAcceptResult ShippingAccept(string acceptDigestCode)
    {
    string strXml = "";
    try
    {
        xmlRequest = new System.Xml.XmlDocument();
        xmlRequest.LoadXml(@"<?xml version=""1.0""?>
     <ShipmentAcceptRequest>
       <Request>
          <TransactionReference>
         <CustomerContext>TR01</CustomerContext>
         <XpciVersion>1.0001</XpciVersion>
          </TransactionReference>
          <RequestAction>ShipAccept</RequestAction>
          <RequestOption>01</RequestOption>
       </Request>
       <ShipmentDigest>" + acceptDigestCode + "</ShipmentDigest></ShipmentAcceptRequest>");

        byte[] bb = new System.Text.ASCIIEncoding().GetBytes(string.Format(XML_CONNECT, sAccessCode.Trim(), sUserId.Trim(), sPassword.Trim()));
        byte[] bResponse = null; 
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        ms.Write(bb, 0, bb.Length);
        xmlRequest.Save(ms);
        bb = ms.ToArray();
        xmlRespone = new XmlDocument();
        string serverName = (testMode) ? "wwwcie" : "onlinetools.ups.com";
        serverName = string.Format(UPS_SERVICE_URL, serverName, ShipRequestTypes.ShipAccept);

        using (var client = new NoKeepAlivesWebClient())
        {
        bResponse = client.UploadData(serverName, "POST", bb);
        }

        if (bResponse != null)
        {
        xmlRespone.LoadXml(System.Text.ASCIIEncoding.ASCII.GetString(bResponse));
        }
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show("ShippingAccept " + ex.Message);
        System.Windows.Forms.MessageBox.Show(strXml);
    }
    return new ShippingAcceptResult(xmlRespone);

}

public class NoKeepAlivesWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
        ((HttpWebRequest)request).KeepAlive = false;
        }

        return request;
    }
}

在我没有set KeepAlive = false 之前,我也收到了相同的错误消息,但现在当我设置KeepAlive = false 时,有时也会出现相同的连接关闭相关错误。

告诉我错误是特定于任何电脑的吗?

我应该像 KeepAlive 选项那样为 webclient 设置超时值吗?

所以请有人把我带到正确的方向来摆脱这个错误。

告诉我发生错误的所有可能原因。谢谢

【问题讨论】:

  • 也许堆栈跟踪将有助于找到答案。
  • 如果是 https,请确保您接受证书(编辑),不要等待,如果它有时有效,但其他人无法访问相同的 url,请忽略它

标签: c# xml webclient xmldocument ups


【解决方案1】:

实际上这行代码解决了我的问题

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; //768 for TLS 1.1 and 3072 for TLS 1.2
//ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
//System.Net.ServicePointManager.ServerCertificateValidationCallback += (send, certificate, chain, sslPolicyErrors) => { return true; };
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

我与 ServicePointManager 一起使用的更多代码 sn-p

using (var client = new NoKeepAlivesWebClient())
{
    bResponse = client.UploadData(serverName, "POST", bb);
}

/// Certificate validation callback.
/// </summary>
private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
    // If the certificate is a valid, signed certificate, return true.
    if (error == System.Net.Security.SslPolicyErrors.None)
    {
    return true;
    }

    Console.WriteLine("X509Certificate [{0}] Policy Error: '{1}'",
    cert.Subject,
    error.ToString());

    return false;
}

public class NoKeepAlivesWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
        ((HttpWebRequest)request).KeepAlive = false;
        ((HttpWebRequest)request).Timeout = 60000;
        }

        return request;
    }
}

【讨论】:

  • 看起来ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072; 解决了我在一个实施了很长时间但几天前突然停止的问题。可能在一月更新之后。
  • ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 |安全协议类型.Tls12;是我指的那条线
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-31
  • 2018-01-31
  • 2017-09-21
相关资源
最近更新 更多