項目使用了netcore的注入技術,所以使用HttpClientFactory需要按照以下操作進行
-
項目通過AddHttpClient添加HttpClient服務進行使用
爲了避免出現證書錯誤的問題需要
設置 ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true, 忽略證書var httpClient = services.AddHttpClient(“https”).ConfigurePrimaryHttpMessageHandler(sp => new System.Net.Http.HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true,
ClientCertificateOptions = System.Net.Http.ClientCertificateOption.Automatic
});
2.在項目中使用擴展的HttpContextCC全局類獲取HttpClient服務
//從IOC注入中獲取IHttpClientFactory服務
var httpClientFactory = HttpContextCC.Current.RequestServices.GetRequiredService<IHttpClientFactory>();
var client = httpClientFactory.CreateClient("https");
3.然後就可以使用獲取到client進行後續的操作了