Search code examples
c#.netsystem.net.httpwebrequest

HttpWebRequest returns error in c#, works in simple php example


I have working php example, which does its job, but can not make the same in .NET - returning

System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel. at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) at System.Net.HttpWebRequest.GetRequestStream() at

php code:

$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 Code

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()))
{
}

I have tried many variations of ignoring cert errors, or playing with tls ssl ver sions etc, but none seems to be working I have tried many variations of ignoring cert errors, or playing with tls ssl ver sions etc, but none seems to be working.

(about duplication suggestions, I think I've tried them all, none solved my issue)


Solution

  • I don't know why, but turns out sometimes specifying correct ContentLength might cause this problem. Just removing req.ContentLength = buffer.Length; solved the issue.