C# WebClient 异常:底层连接已关闭 [英] C# WebClient Exception: The underlying connection was closed

查看:35
本文介绍了C# WebClient 异常:底层连接已关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i am sending xml data to UPS web site, some time i am getting response and some time i am getting the Exception: The underlying connection was closed

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

see a sample code which send xml to a specific 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 然后也有一段时间关闭相同的连接相关错误.

before i did not set KeepAlive = false then also i was getting same error message but now when i set KeepAlive = false then also some time getting the same connection close related error.

告诉我该错误特定于任何电脑?

tell me the error is specific to any pc?

我是否应该像 KeepAlive 选项一样为 webclient 设置超时值?

should i set timeout value for webclient like KeepAlive option?

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

so please someone drive me to right direction to get rid of this error.

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

tell me all possible reason for which error is occurring. thanks

推荐答案

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

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

这篇关于C# WebClient 异常:底层连接已关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆