C#用httpclient发出https请求

时间:2017-06-08 17:32:45

标签: c# ssl https dotnet-httpclient

UPD:此代码适用于Windows Server 2012,但在Windows 7,8,10中无效。我不知道为什么

我正在尝试向仅允许https连接的某些服务发出请求。但我得到错误

The request was aborted: Could not create SSL/TLS secure channel

我的代码

using (var client = new HttpClient())
{
    ServicePointManager.Expect100Continue = true;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
    ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
    var response = await client.PostAsync(ApiAddress, content);
    var xml = await response.Content.ReadAsStringAsync();

    var transaction = DeserializeXml<StationsResponseTransaction>(xml);
    return transaction;
}

此服务提供了证书(.crt)和私钥(.pem)文件。也许我需要使用这些文件?但是如何?

更新 我尝试创建pfx证书并将其添加到WebRequestHandler

WebRequestHandler handler = new WebRequestHandler();
X509Certificate2 certificate = new X509Certificate2("Certificate.pfx", "password");
handler.ClientCertificates.Add(certificate);

并在客户端new HttpClient(handler)

中使用处理程序

但是我得到了同样的错误

更新:刚刚在邮递员中测试了这个请求 - 当google crhome接受服务器证书时,工作正常。但是如何从C#httpclient接受证书?

ServicePointManager的{​​{1}}事件未被称为

1 个答案:

答案 0 :(得分:0)

从.pfx制作.cer文件,然后将其安装到本地的受信任文件夹中。 然后从.pfc创建client .cer,并在解决方案中使用它(不要安装它)。