如何使用 .Net Core 中的单个 HttpClient 实例针对不同的请求发送不同的客户端证书?

Don*_*mmy 5 .net c# dotnet-httpclient .net-core asp.net-core

的建议HttpClient重用单个实例。但是从 API 来看,添加证书的方式似乎是在实例上,而不是每个请求。例如,如果我们添加两个证书,我们如何确保“cert 1”仅发送到“one.somedomain.com”?

//A handler is how you add client certs (is there any other way?)
var _clientHandler = new HttpClientHandler();

//Add multiple certs
_clientHandler.ClientCertificates.Add(cert1);
_clientHandler.ClientCertificates.Add(cert2);
_clientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;


//Pretend this is our long-living HttpClient
var client = new HttpClient(_clientHandler);

//Now if we make a post request, will both certs be used?
using (HttpResponseMessage response = _client.PostAsync("https://one.somedomain.com", content).Result)
{
    //...elided...
 }
Run Code Online (Sandbox Code Playgroud)

小智 -3

这是建议,但是,您可以使用“using”语句。

一旦 HttpClient 是 IDisposable,您应该使用类似的东西

using(var client = new HttpClient(_clientHandler))
{
    //Your code here
}
Run Code Online (Sandbox Code Playgroud)

  • Microsoft 特别不建议这样做,并且会引入性能问题、内存泄漏和连接句柄泄漏 (2认同)