X509Certificate2 cer = new X509Certificate2(@"path", "********", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); HttpClientHandler handler = new HttpClientHandler(); handler.UseDefaultCredentials = true; handler.ClientCertificateOptions = ClientCertificateOption.Automatic; HttpClient httpClient = new HttpClient(handler); var stringContent = new StringContent(requestXml, System.Text.Encoding.UTF8); var req = await httpClient.PostAsync("https://api.mch.weixin.qq.com/secapi/pay/refund", stringContent);
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; //总是接受 } ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10;
update: I ran the exact same thing on Windows 7 and it worked exactly as needed.
// using System.Net.Http;
// using System.Security.Authentication;
// using System.Security.Cryptography.X509Certificates;
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.SslProtocols = SslProtocols.Tls12;
handler.ClientCertificates.Add(new X509Certificate2("cert.crt"));
var client = new HttpClient(handler);
var result = client.GetAsync("https://apitest.startssl.com").GetAwaiter().GetResult();
var clientCertificate = await HttpContext.Connection.GetClientCertificateAsync();
if(clientCertificate!=null)
return new ContentResult() { Content = clientCertificate.Subject };
https://blog.pedrofelix.org/2012/12/16/using-httpclient-with-ssltls/
HttpClientHandler and WebRequestHandler.
The first option is to explicitly configure the HttpClient with a HttpClientHandler instance, containing its ClientCertificateOptions property set to Automatic.
var client = new HttpClient(
new HttpClientHandler{
ClientCertificateOptions = ClientCertificateOption.Automatic
});
// ...
For classical scenarios (e.g. console, WinForms or WPF applications) there is a second option using the WebRequestHandler, which provides more control over the configuration.
var clientHandler = new WebRequestHandler() clientHandler.ClientCertificates.Add(cert); var client = new HttpClient(clientHandler)
where cert is a X509Certificate2 instance representing the client certificate.
This instance can be constructed directly from a PFX file or obtained from a Windows certificate store
X509Store store = null; try { store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly); // select the certificate from store.Certificates ... } finally { if(store != null) store.Close(); }