繁体   English   中英

C#使用httpclient发出https请求

[英]C# making https request with 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)使用处理new HttpClient(handler)

但是我有同样的错误

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

未调用ServicePointManagerServerCertificateValidationCallback事件

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM