c# – Http post error:远程主机强行关闭现有连接

前端之家收集整理的这篇文章主要介绍了c# – Http post error:远程主机强行关闭现有连接前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道有很多类似的帖子,但我还没有找到解决方案.我试图将一些xml发布到MPI网关,但不断收到以下错误

Unable to read data from the transport connection: An existing
connection was forcibly closed by the remote host.

下面是我目前使用的代码,但我已经尝试了几乎所有我能想到的不同方法,它们都返回相同的错误

  1. string result = "";
  2.  
  3. string xml = "<TNSAuthRequest><CardNumber>0123456789</CardNumber><ExpiryDate>1801</ExpiryDate><PurchaseAmt>750</PurchaseAmt><CurrencyCode>826</CurrencyCode><CurrencyExponent>2</CurrencyExponent><CountryCode>826</CountryCode><MerchantName>Mayflower</MerchantName><MerchantId>0123456789</MerchantId><MerchantData>abcdefghijklmnopqrstuvwxyz0123456789</MerchantData><MerchantUrl>example.com</MerchantUrl><NotificationURL>example.com/basket</NotificationURL></TNSAuthRequest>";
  4.  
  5. var url = "https://mpi.securecxl.com";
  6. byte[] bytes = System.Text.Encoding.ASCII.GetBytes("xmldata=" + xml.ToString());
  7.  
  8. ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateRemoteCertificate);
  9.  
  10. var req = (HttpWebRequest)WebRequest.Create(url);
  11. req.AllowWriteStreamBuffering = true;
  12. req.ContentType = "text/xml";
  13. req.Method = "POST";
  14. //req.ContentLength = bytes.Length;
  15. req.KeepAlive = false;
  16. req.ProtocolVersion = HttpVersion.Version10;
  17. req.ServicePoint.ConnectionLimit = 1;
  18. //req.Timeout = -1;
  19.  
  20. try
  21. {
  22. using (var writer = new StreamWriter(req.GetRequestStream(),Encoding.ASCII))
  23. {
  24. writer.WriteLine(bytes);
  25. }
  26. using (WebResponse resp = req.GetResponse())
  27. {
  28. using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
  29. {
  30. result = sr.ReadToEnd().Trim();
  31. }
  32. }
  33. }
  34. catch (Exception ex)
  35. {
  36. result = ex.Message + "<br />" + ex.InnerException.Message + "<br /><br />" + xml.Replace("<","&lt;");
  37. }
  38.  
  39. ViewBag.result = result;

如果任何人都可以看到可能导致此错误代码可能出错的任何内容,或者如果它最有可能在他们的结尾出现问题,我基本上会徘徊吗?尝试在我的localhost,我们的实时服务器和我自己的私有服务器(具有完全不同的IP)上运行,并且仍然得到相同的结果.

有任何想法吗?

解决方法

我认为是因为你连接到“https”网址.在这种情况下,您必须在代码添加以下行.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

它将接受您的请求的“ssl”协议. “ServicePointManager.ServerCertificateValidationCallback”处理程序只控制证书有效性.

猜你在找的C#相关文章