将Curl命令转换为C#

时间:2018-02-12 09:20:40

标签: c# asp.net curl httpwebrequest x509certificate2

我正在尝试将Curl命令转换为C#,这是命令的外观

curl -E <partner>.crt --key <partner>.key https://APIDomain/returns/?wsdl -v --no-alpn

这将返回一个wsdl文件,现在如何将此代码转换为c#? 注意:API要求我使用X509证书对呼叫进行身份验证,这就是此处使用.crt.key文件的原因。 我试图通过下面的代码实现相同,但它会抛出错误

  

fiddler.network.https&GT;对APIDomain /(#1)的HTTPS握手失败。 System.IO.IOException无法从传输连接读取数据:远程主机强制关闭现有连接。 &LT;远程主机强制关闭现有连接   在提琴手上

 string host = @"https://APIDomain/returns/?wsdl";
            string certName = @"C:\Cert\mydomain.pfx";
            string password = @"xxxxxxxxx";

            try
            {
                X509Certificate2 certificate = new X509Certificate2(certName, password);

                ServicePointManager.CheckCertificateRevocationList = false;
                ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
                ServicePointManager.Expect100Continue = true;
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(host);
                req.PreAuthenticate = true;
                req.AllowAutoRedirect = true;
                req.ClientCertificates.Add(certificate);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                string postData = "login-form-type=cert";
                byte[] postBytes = Encoding.UTF8.GetBytes(postData);
                req.ContentLength = postBytes.Length;

                Stream postStream = req.GetRequestStream();
                postStream.Write(postBytes, 0, postBytes.Length);
                postStream.Flush();
                postStream.Close();
                WebResponse resp = req.GetResponse();

                Stream stream = resp.GetResponseStream();
                using (StreamReader reader = new StreamReader(stream))
                {
                    string line = reader.ReadLine();
                    while (line != null)
                    {
                        Console.WriteLine(line);
                        line = reader.ReadLine();
                    }
                }

                stream.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

1 个答案:

答案 0 :(得分:1)

您可以尝试以下代码吗?

var handler = new HttpClientHandler();
    handler.ClientCertificateOptions = ClientCertificateOption.Manual;
    handler.SslProtocols = SslProtocols.Tls12;
    handler.ClientCertificates.Add(new X509Certificate2("<partner>.crt", key));
    var client = new HttpClient(handler);
    var result = client.GetAsync("https://APIDomain/returns/?wsdl").GetAwaiter().GetResult();