配置HttpClientFactory

时间:2018-06-22 14:12:11

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

我需要在 HttpClientFactory 中添加证书。带有HttpClient的旧实现看起来像这样:

var cookieContainer = new CookieContainer();
var handler = new HttpClientHandler { CookieContainer = cookieContainer };

var basePath = Directory.GetCurrentDirectory();
var certificatePath = Path.Combine(basePath, certPath);
var fileExists = File.Exists(certificatePath);

if (!fileExists)
    throw new ArgumentException(certificatePath);

var certificate = new X509Certificate2(certificatePath, certPwd);
handler.ClientCertificates.Add(certificate);

using (var client = new HttpClient(handler))
{
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(accept));
    client.DefaultRequestHeaders.Add("ApiKey", apiKey);

    var body = new { UserName = username, UserPassword = password };
    var jsonBody = JsonConvert.SerializeObject(body);
    var content = new StringContent(jsonBody, Encoding.UTF8, contentType);

    var loginResponse = client.PostAsync(loginEndpoint, content).Result;
 }

但是当我尝试从 ConfigurePrimaryHttpMessageHandler 获取连接时,无法在处理程序中设置 ClientCertificates 。如何解决呢?

更新

public void SetUpHttpClients(IServiceCollection services)
{
        var loginEndpoint = Path.Combine(baseApi, "api/authentication);
        var fileExists = File.Exists(certificatePath);

        if (!fileExists)
            throw new ArgumentException(certificatePath);

        var certificate = new X509Certificate2(certificatePath, certPwd);

        services.AddHttpClient("TestClient", client =>
        {
        client.BaseAddress = new Uri(baseApi);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(accept));
        client.DefaultRequestHeaders.Add("ApiKey", apiKey);

        var body = new { Username = username, Password = password };
        var jsonBody = JsonConvert.SerializeObject(body);
        var content = new StringContent(jsonBody, Encoding.UTF8, contentType);

        var loginResponse = client.PostAsync(loginEndpoint, content).Result;

        }).ConfigurePrimaryHttpMessageHandler(() =>
        {
            var cookieContainer = new CookieContainer();
            var handler = new HttpClientHandler
            {
                CookieContainer = cookieContainer
            };
            handler.ClientCertificates.Add(certificate);
            return handler;
}); 

1 个答案:

答案 0 :(得分:6)

该异常消息是准确的。

致电ClientCertificates.Add(certificate);与以前一样没事

services.AddHttpClient("TestClient", client => {
    client.BaseAddress = new Uri(baseApi);
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(accept));
    client.DefaultRequestHeaders.Add("ApiKey", apiKey);
})
.ConfigurePrimaryHttpMessageHandler(() => {
    var handler = new HttpClientHandler {
        CookieContainer = cookieContainer
    };
    handler.ClientCertificates.Add(certificate);
    return handler;
});