本文章介绍在 ASP.NET Core 中使用 HttpClient 发起 Http 请求
由于实例化 HttpClient 类将耗尽重负载下可用的插槽数,会导致 SocketException 错误
所以使用最佳实践 IHttpClientFactory 创建 HttpClient
先决条件
.NET 8 SDK
正确使用 HttpClient 的示例
在使用 HttpClient 时应该使用单例模式
public class GoodController : ApiController
{
private static readonly HttpClient HttpClient;
static GoodController()
{
HttpClient = new HttpClient();
}
}
复制代码
使用 IHttpClientFactory 实现
首先需要在代码中引入 HttpClientFactory
基本使用
// 在容器中注册服务
services.AddHttpClient();
复制代码
使用构造函数注入使用 IHttpClientFactory
IHttpClientFactory _httpClientFactory;
public HomeController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[HttpGet]
public async void Get()
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:5000/Home/Index");
var client = _httpClientFactory.CreateClient();
var response = await client.SendAsync(request);
var httpContent = response.Content;
var result = await httpContent.ReadAsStringAsync();
}
复制代码
命名不同的配置
// 在容器中注册服务
services.AddHttpClient();
services.AddHttpClient("local", c =>
{
c.BaseAddress = new Uri("http://localhost:5000");
c.DefaultRequestHeaders.Add("Accept", "application/json");
});
复制代码
使用构造函数注入使用 IHttpClientFactory
IHttpClientFactory _httpClientFactory;
public HomeController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[HttpGet]
public async void Get()
{
var client = _httpClientFactory.CreateClient("local");
var response = await client.GetAsync("Home/Index");
HttpContent httpContent = response.Content;
var result = await httpContent.ReadAsStringAsync();
}
复制代码
参考文档
Docs.Microsoft - HttpClient Class
评论