4

我需要在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;
}); 
4

1 回答 1

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;
});
于 2018-06-22T15:27:05.913 回答