一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - ASP.NET教程 - 如何在ASP.NET Core中使用HttpClientFactory

如何在ASP.NET Core中使用HttpClientFactory

2021-12-10 15:47碼農讀書 ASP.NET教程

這篇文章主要介紹了如何在ASP.NET Core中使用HttpClientFactory,幫助大家更好的理解和學習使用.net技術,感興趣的朋友可以了解下

ASP.Net Core 是一個開源的,跨平臺的,輕量級模塊化框架,可用它來構建高性能的Web程序,這篇文章我們將會討論如何在 ASP.Net Core 中使用 HttpClientFactory。

為什么要使用 HttpClientFactory

可以用 HttpClientFactory 來集中化管理 HttpClient,工廠提供了對 HttpClient 的創建,配置和調度,值得一提的是:HttpClient 一直都是 Http 請求業務方面的一等公民。

HttpClient 雖好,但它有一些缺點:

  • 創建太多的 HttpClient 是一種低效的行為,因為當一個新客戶端連接到遠程 Server 時,你的應用程序還需要承擔著重連遠程 Server 的開銷。
  • 如果每一個 request 都創建一個 HttpClient,當應用程序負載過大, Socket 必將耗盡,比如默認情況下 HttpClient 會維持至少4分鐘的 Connection 連接。

所以推薦的做法是創建一個可供復用的共享式 HttpClient 實例,如果你要打破沙鍋問到低的話,即使是創建共享式的 HttpClient 也會有很多問題,比如它會無視 DNS 緩存生效,那怎么辦呢?可以用 .NET Core 2.1 引入的 HttpClientFactory 來解決此問題。。。用它來統一化的高效管理 HttpClient。

使用 HttpClientFactory

HttpClientFactory 有兩種使用方式。

  • NamedClient
  • TypedClient

所謂的 NamedClient 就是注冊帶有標記的 HttpClient 到 HttpClientFactory 工廠中,下面的代碼展示了一個名為 IDGCustomApi 的 HttpClient 的工廠注冊。

?
1
2
3
4
5
6
7
8
9
10
11
12
        // 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,我想你肯定有點懵逼了,沒關系,我現在就來自定義 HttpClient, 然后通過 AddHttpClient() 注冊到容器中。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    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 通過構造函數方式進行注入,參考如下代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    [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;
        }
    }

如何在ASP.NET Core中使用HttpClientFactory

從 IHttpClientFactory 的默認實現 DefaultHttpClientFactory 的源碼也可以看出,httpClient 所關聯的 HttpMessageHandler 和 Options 都被工廠跟蹤和管控。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    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的詳細內容,更多關于ASP.NET Core使用HttpClientFactory的資料請關注服務器之家其它相關文章!

原文鏈接:https://mp.weixin.qq.com/s/XYowRcW2DFAy0YgYAGExYw

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 98色花堂永久地址国产精品 | 9久热久爱免费精品视频在线观看 | 日韩一区二区中文字幕 | 逼逼狗影院 | 天天夜夜草草久久伊人天堂 | 国产成人啪精品视频站午夜 | 青柠在线完整高清观看免费 | 国产chinese男男gaygay | 冰漪丰满大乳人体图片欣赏 | 性派对videofreeparty| 九九九九视频 | www.大逼色| 好姑娘在线完整版视频 | 国产亚洲视频网站 | 天天做天天爱天天爽综合网 | 亚洲成在人网站天堂一区二区 | 高h短篇辣肉各种姿势bl | 百合女女师生play黄肉黄 | 91高清国产经典在线观看 | 贵妇的私人性俱乐部 | 2019中文字幕| 国产chinese男男gaygay | 国产成人高清精品免费5388密 | 久久视频精品3线视频在线观看 | 91国语自产拍在线观看 | 国产精品1区2区 | 红色播放器 | 国产亚洲精品91 | 欧美三茎同入 | 男人使劲躁女人视频免费 | 天天干天天操天天碰 | 99精品热线在线观看免费视频 | 青青色在线 | 欧美同性gayvidoes | 国产欧美一区二区三区免费看 | 国内精品一区二区三区东京 | freee×xx性欧美| 久久久久综合 | 506rr亚洲欧美| 亚洲精品www久久久久久久软件 | 高清国产在线观看 |