如何在ASP.NET Core中使用HttpClientFactory
ASP.Net Core 是一個開源的,跨平臺的,輕量級模塊化框架,可用它來構(gòu)建高性能的Web程序,這篇文章我們將會討論如何在 ASP.Net Core 中使用 HttpClientFactory。
為什么要使用 HttpClientFactory
可以用 HttpClientFactory 來集中化管理 HttpClient,工廠提供了對 HttpClient 的創(chuàng)建,配置和調(diào)度,值得一提的是:HttpClient 一直都是 Http 請求業(yè)務(wù)方面的一等公民。
HttpClient 雖好,但它有一些缺點:
- 創(chuàng)建太多的 HttpClient 是一種低效的行為,因為當(dāng)一個新客戶端連接到遠(yuǎn)程 Server 時,你的應(yīng)用程序還需要承擔(dān)著重連遠(yuǎn)程 Server 的開銷。
- 如果每一個 request 都創(chuàng)建一個 HttpClient,當(dāng)應(yīng)用程序負(fù)載過大, Socket 必將耗盡,比如默認(rèn)情況下 HttpClient 會維持至少4分鐘的 Connection 連接。
所以推薦的做法是創(chuàng)建一個可供復(fù)用的共享式 HttpClient 實例,如果你要打破沙鍋問到低的話,即使是創(chuàng)建共享式的 HttpClient 也會有很多問題,比如它會無視 DNS 緩存生效,那怎么辦呢?可以用 .NET Core 2.1 引入的 HttpClientFactory 來解決此問題。。。用它來統(tǒng)一化的高效管理 HttpClient。
使用 HttpClientFactory
HttpClientFactory 有兩種使用方式。
- NamedClient
- TypedClient
所謂的 NamedClient 就是注冊帶有標(biāo)記的 HttpClient 到 HttpClientFactory 工廠中,下面的代碼展示了一個名為 IDGCustomApi 的 HttpClient 的工廠注冊。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient("IDGCustomApi", client =>
{
client.BaseAddress = new Uri("https://localhost:6045/");
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("User-Agent", "IDG");
});
services.AddControllers();
}
所謂的 TypedClient 就是注冊一個你自定義的 HttpClient,我想你肯定有點懵逼了,沒關(guān)系,我現(xiàn)在就來自定義 HttpClient, 然后通過 AddHttpClient() 注冊到容器中。
public class CustomHttpClient
{
public HttpClient Client { get; }
public CustomHttpClient(HttpClient client)
{
Client = client;
}
}
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient<CustomHttpClient>(client => client.BaseAddress = new Uri("https://localhost:6045/"));
services.AddControllers();
}
}
注入 Controller
為了能夠在 Controller 中使用,可以將 IHttpClientFactory 通過構(gòu)造函數(shù)方式進(jìn)行注入,參考如下代碼:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private IHttpClientFactory httpClientFactory;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IHttpClientFactory httpClientFactory)
{
this.httpClientFactory = httpClientFactory;
}
[HttpGet]
public async Task<string> Get()
{
var httpClient = httpClientFactory.CreateClient("IDGCustomApi");
string html = await httpClient.GetStringAsync("http://bing.com");
return html;
}
}

從 IHttpClientFactory 的默認(rèn)實現(xiàn) DefaultHttpClientFactory 的源碼也可以看出,httpClient 所關(guān)聯(lián)的 HttpMessageHandler 和 Options 都被工廠跟蹤和管控。
internal class DefaultHttpClientFactory : IHttpClientFactory, IHttpMessageHandlerFactory
{
public HttpClient CreateClient(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
HttpMessageHandler handler = CreateHandler(name);
HttpClient httpClient = new HttpClient(handler, disposeHandler: false);
HttpClientFactoryOptions httpClientFactoryOptions = _optionsMonitor.Get(name);
for (int i = 0; i < httpClientFactoryOptions.HttpClientActions.Count; i++)
{
httpClientFactoryOptions.HttpClientActions[i](httpClient);
}
return httpClient;
}
public HttpMessageHandler CreateHandler(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
ActiveHandlerTrackingEntry value = _activeHandlers.GetOrAdd(name, _entryFactory).Value;
StartHandlerEntryTimer(value);
return value.Handler;
}
}
譯文鏈接:https://www.infoworld.com/article/3276007/how-to-work-with-httpclientfactory-in-aspnet-core.html
以上就是如何在ASP.NET Core中使用HttpClientFactory的詳細(xì)內(nèi)容,更多關(guān)于ASP.NET Core使用HttpClientFactory的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
.NET 6開發(fā)TodoList應(yīng)用之實現(xiàn)ActionFilter
Filter在.NET Web API項目開發(fā)中也是很重要的一個概念,它運(yùn)行在執(zhí)行MVC響應(yīng)的Pipeline中執(zhí)行,允許我們將一些可以在多個Action之間重用的邏輯抽取出來集中管理。本文將詳細(xì)介紹一下.NET 6如何實現(xiàn)ActionFilter,感興趣的可以學(xué)習(xí)一下2021-12-12
asp.net 網(wǎng)頁動態(tài)查詢條件的實現(xiàn)
最近有一個需求,會在 mongodb 中插入各種類型的數(shù)據(jù),算是記錄業(yè)務(wù)日志的數(shù)據(jù)庫吧。因為業(yè)務(wù)對象類型都不同,所以插入的數(shù)據(jù)格式也完全不同2012-10-10
OpenCV 3.1.0+VS2015開發(fā)環(huán)境配置教程
這篇文章主要為大家詳細(xì)介紹了OpenCV 3.1.0+VS2015開發(fā)環(huán)境配置教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11
顯示非站點目錄及映射網(wǎng)絡(luò)磁盤路徑的圖片
本文就將教你怎樣顯示非站點目錄下的圖片,你可以顯示站點所在服務(wù)器所有驅(qū)動器目錄的圖片,以及映射網(wǎng)絡(luò)磁盤路徑的圖片,感興趣的朋友可以了解下就當(dāng)鞏固知識了或許對你學(xué)習(xí).net有所幫助2013-02-02
ASP.NET Core設(shè)置URLs的方法匯總(完美解決.NET 6項目局域網(wǎng)IP地址遠(yuǎn)程無法訪問的
近期在dotnet項目中遇到這樣的問題.net6 運(yùn)行以后無法通過局域網(wǎng)IP地址遠(yuǎn)程訪問,整理出解決問題的五種方式方法,感興趣的朋友一起看看吧2023-11-11

