簡體   English   中英

如何使用 .Net Core 中的單個 HttpClient 實例針對不同的請求發送不同的客戶端證書?

[英]How send different client certificates on different requests with a single instance of HttpClient in .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...
 }

對不起。 年底工作量大。 你可以嘗試實現這樣的事情:

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;
            }
        }
    }
}

只是一個想法,沒有測試過。 或者,您也可以在RequestMessage實例中使用Headers集合。 本文涵蓋的主題: https : //damienbod.com/2019/09/07/using-certificate-authentication-with-ihttpclientfactory-and-httpclient/

這是建議,但是,您可以使用“using”語句。

一旦 HttpClient 是 IDisposable,你應該使用類似

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM