我需要HttpClientFactory
用于连接到外部 api。中的代码Startup.cs
看起来像这样
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;
});
我已经用 HttpClientFactory 在 MessageController 中添加了这段代码,
public class MessagesController : Controller
{
private readonly IHttpClientFactory _httpClientFactory;
public ValuesController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[HttpGet]
public IActionResult GetMessages()
{
var client = _httpClientFactory.CreateClient("TestClient");
var result = client.GetStringAsync("/api/messages");
return Ok(result);
}
}
但是当我尝试连接并从中获取消息时HttpClientFactory
,我收到此错误:
无法加载资源:net::ERR_CONNECTION_RESET,404 - BadRequest