ASP.NET Core 中的 IHttpClientFactory
說明
在 .NET 程式中,可以用 HttpClient 或 WebClient 這兩種類別來抓取網頁。而在 ASP.NET Core 中,提供了 IHttpClientFactory 來取得 HttpClient 的 instance。一開始覺得好像沒什麼差別,但在官方文件中提到:自動管理可避免在手動管理 HttpClient 存留期時所發生的常見 DNS (網域名稱系統)問題
。想想既然這樣用沒壞處,也不用爭論要用 HttpClient 或 WebClient,那就照官方的建議吧。
使用方式
首先要先在 Startup.cs 做註冊:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddHttpClient();
}
之後在 controller 的使用也相當簡單,有用過 HttpClient 的一定覺得不難:
public HomeController(ILogger<HomeController> logger, IHttpClientFactory httpClientFactory)
{
_logger = logger;
_httpClientFactory = httpClientFactory;
}
public async Task<ActionResult> TestHttp()
{
var request = new HttpRequestMessage(HttpMethod.Get, "https://www.google.com");
HttpClient client = _httpClientFactory.CreateClient();
HttpResponseMessage response = await client.SendAsync(request);
string content = string.Empty;
if (response.IsSuccessStatusCode)
{
content = await response.Content.ReadAsStringAsync();
}
return Content(content);
}
參考資料