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

时间:2019-12-18 15:07:06

标签: c# .net asp.net-core .net-core dotnet-httpclient

HttpClient的推荐是对reuse a single instance的推荐。但是从API来看,添加证书的方式似乎是在实例上,而不是每个请求上。如果添加两个证书,例如,如何确保仅将“证书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...
 }

2 个答案:

答案 0 :(得分:1)

对不起。年末很多工作。 can可以尝试实现这样的东西:

public class CustomHttpHandler : HttpClientHandler
{
    private readonly Dictionary<string, X509Certificate> _certMap;

    public CustomHttpHandler():base()
    {
        _certMap = new Dictionary<string, X509Certificate>() { { "server1name", new X509Certificate("cert1") }, { "server2name", new X509Certificate("cert2") } };
    }

    protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
    {
        string serverName = request.RequestUri.Host;
        if (ClientCertificates.Contains(_certMap[serverName]))
        {
            try
            {
                var response = await base.SendAsync(request, cancellationToken);
                return response;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
                throw;
            }
        }
        else
        {
            ClientCertificates.Clear();
            ClientCertificates.Add(_certMap[serverName]);

            try
            {
                var response = await base.SendAsync(request, cancellationToken);
                return response;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
                throw;
            }
        }
    }
}

只是一个主意,未经测试。 或者,您也可以在Headers实例中使用RequestMessage集合。 本文介绍了以下主题:https://damienbod.com/2019/09/07/using-certificate-authentication-with-ihttpclientfactory-and-httpclient/

答案 1 :(得分:-3)

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

一旦HttpClient是一个IDisposable,您应该使用类似

using(var client = new HttpClient(_clientHandler))
{
    //Your code here
}