Asp.net Core Flurl.Http 结合IHttpClientFactory管理HttpClient生命周期

Asp.net Core, 在我用过的多种Http REST 客户端:

RestSharp

WebApiClient

Refit

Flurl

中,Flurl可以说是最符合我口味的,用起来那可真的顺滑无比。

不过它因为出现的比较早,并没有使用asp.net core中的IHttpClientFactory 管理HttpClient实例,而是自己管理。一般是根据host来缓存一个HttpClient实例,比如你请求所有的https://www.baidu.com/ 都用一个缓存的实例,这样可能会有些问题,比如Dns更新等;

对于我们有着用IHttpClientFactory的执念,Flurl也是支持的:

简单写法

注入HttpClient

public void ConfigureServices(IServiceCollection services)
{
	 //...

	services.AddHttpClient();

	//...
}

使用

private readonly IFlurlClient _flurlClient;

public CommonController(IHttpClientFactory httpClientFactory)
{
	_flurlClient = new FlurlClient(httpClientFactory.CreateClient());
}

实战用法

添加api业务实体类

    public class TestFlurlHttpClient
    {
        private readonly IFlurlClient _flurlClient;

        public TestFlurlHttpClient(HttpClient httpClient)
        {
            _flurlClient = new FlurlClient(httpClient);
        }

        public async Task<PassportUserModel> GetUserByPid(int pid)
        {
            var result = await _flurlClient.Request($"api/v1/member/user/getbypid?pid={pid}").GetJsonAsync<PassportApiResult<PassportUserModel>>();
            return result.Data;
        }
    }

注入HttpClient

public void ConfigureServices(IServiceCollection services)
{
   //...

     services.AddHttpClient<TestFlurlHttpClient>("memberclient", c =>
     {
    	 c.BaseAddress = new System.Uri("http://172.16.3.119:5001/");
     });
     
     //或
     //services.AddHttpClient<ITestFlurlHttpClient,TestFlurlHttpClient>("memberclient", c =>
     //{
    	// c.BaseAddress = new System.Uri("http://172.16.3.119:5001/");
     //});

  //...
}

使用

private readonly TestFlurlHttpClient _testFlurlHttpClient;

public CommonController(TestFlurlHttpClient testFlurlHttpClient)
{
    _testFlurlHttpClient = testFlurlHttpClient;
}

如丝顺滑,谁用谁知道;

了解更多还是看文档吧 : https://flurl.dev/docs

posted @ 2021-08-02 18:11  乔达摩  阅读(86)  评论(0编辑  收藏  举报