HttpWebRequest在C#中返回错误,可在简单的php示例中使用

时间:2019-02-28 11:31:22

标签: c# .net system.net.httpwebrequest

我有一个工作正常的php示例,它可以完成工作,但在.NET中无法做到相同-返回

  

System.Net.WebException:请求已中止:无法创建SSL / TLS安全通道。在位于System.Net.HttpWebRequest.GetRequestStream()处的System.Net.HttpWebRequest.GetRequestStream()处

php代码:

$curl = curl_init();
$post_fields = "xxxxxx&msg_type=aaa";
$submit_url = "https://ecommerce.........";
Curl_setopt($curl, CURLOPT_SSLVERSION, 1); //0 
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, '0');
curl_setopt($curl, CURLOPT_SSLCERT,         getcwd().'/sert.pem');
curl_setopt($curl, CURLOPT_SSLKEYPASSWD,   'XXXXXXXX');
curl_setopt($curl, CURLOPT_URL, $submit_url);
$result = curl_exec($curl);
$info = curl_getinfo($curl);

.NET代码

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string addr1 = "https://ecommerce......";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(addr1);

req.Method = "POST"; // Post method
System.Net.ServicePointManager.ServerCertificateValidationCallback =
    delegate
    {
        return true; // **** Always accept
    };

req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version10;

//Certificate with private key
string certName = "sss.xxx.ee_5300954_merchant_wp";
string certpwd = "xxxxxxxx";
X509Certificate2 cert = new X509Certificate2(@"c:\xxx\xxx\" + certName + ".pem", certpwd);

req.ServerCertificateValidationCallback =
    delegate
    {
        return true; // **** Always accept
    };

req.ClientCertificates.Add(cert);

//req.PreAuthenticate = false;

string langStr = "";
String XML = "description=xxxx&msg_type=SMS";//reader.ReadToEnd();

byte[] buffer = Encoding.ASCII.GetBytes(XML);
req.ContentLength = buffer.Length;

// Wrap the request stream with a text-based writer

Stream writer = req.GetRequestStream();
writer.Write(buffer, 0, buffer.Length);
writer.Close();

WebResponse rsp = req.GetResponse();
String post_response = "";
using (StreamReader responseStream = new StreamReader(rsp.GetResponseStream()))
{
}

我尝试了许多忽略证书错误或使用tls ssl版本等的变种,但似乎无济于事我尝试了许多忽略证书错误或使用tls ssl版本等的变种,但似乎没有工作。

(关于重复建议,我想我已经尝试了全部,没有一个解决了我的问题)

2 个答案:

答案 0 :(得分:0)

PHP要么信任您的服务器端,要么跳过TLS验证,这就是它起作用的原因。您如何测试? API是否与您发送请求的机器在同一台计算机上? 检查一下,也许会有所帮助,因为错误非常少见。 https://support.microsoft.com/en-gb/help/980817/fix-a-net-framework-3-5-based-application-becomes-unresponsive-when-a

答案 1 :(得分:0)

我不知道为什么,但是事实证明有时指定正确的ContentLength可能会导致此问题。 只是删除req.ContentLength = buffer.Length; 解决了这个问题。