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