将 Curl 命令转换为 C#

Convert Curl Command to C#

我正在尝试将 Curl 命令转换为 C#,这就是命令的样子

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

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

fiddler.network.https> HTTPS handshake to APIDomain/ (for #1) failed. System.IO.IOException Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. < An existing connection was forcibly closed by the remote host On Fiddler

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

你能试试下面的代码吗?

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();