C# WebClient 异常:底层连接已关闭

C# WebClient Exception: The underlying connection was closed

我正在向 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 设置超时值?

所以请有人指导我正确的方向来摆脱这个错误。

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

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

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 一起使用的更多代码片段

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;
    }
}