This is the 10th day of my participation in Gwen Challenge

About me

My blog | welcome the attention

The introduction

Microsoft introduced HttpClient in the.net Framework 4.x in consideration of the need to call third-party apis that are often used in back-end development. However, HttpClient has been criticized for many serious problems, such as the inability to close connections immediately, and high performance consumption.

To solve these problems, from. NET Core 2.1 began with the introduction of HttpClientFactory, which addresses all of the pain points of HttpClient. With HttpClientFactory, we don’t need to worry about how to create HttpClient and how to release it. It allows you to create business-specific HttpClients that are friendly and flexible to use in conjunction with DI containers.

This article is a tutorial on how to create and use HttpClient.

Application shows that

First of all,

First of all, no matter how. The first thing we must do is register the service. Add the if code to ConfigureServices in startup. cs

services.AddHttpClient();
Copy the code

Below, visit www.baidu.com and return the corresponding HTML results in three different ways.

First inject IHttpClientFactory

private readonly IHttpClientFactory _httpClientFactory;
public HttpClientController(IHttpClientFactory httpClientFactory)
{
    _httpClientFactory = httpClientFactory;
}
Copy the code

The first way | use directly

This way is the most direct and easy to understand. Create an HttpClient from the factory, and then define the content to make the request and get the result.

[HttpGet("getbaidu")]
public async Task<ActionResult> GetBaidu()
{
    var client = _httpClientFactory.CreateClient();
    client.BaseAddress = new Uri("http://www.baidu.com");
    string result = await client.GetStringAsync("/");
    return Ok(result);
}
Copy the code

The second way | MingMingShi way

The named approach is an encapsulation based on the first approach and is equivalent to defining a global use. But because all configuration information has to be registered in the service, when there are N names, if all information is registered in the serivces, there is always a strange feeling, feeling encapsulation is not humanized.

The first step is to configure the HttpClient service with a specific name in ConfigureServices. The service in case 1 will be configured as follows

services.AddHttpClient("baidu", c =>
{
	c.BaseAddress = new Uri("http://www.baidu.com");
});
Copy the code

Step 2 uses some named httpClient services in the API

The difference is that the CreateClient parameter passes “baidu”, which calls the injected content to initialize the configuration.

[HttpGet("GetBaiduClient")]
public async Task<ActionResult> GetBaiduClient()
{
    var client = _httpClientFactory.CreateClient("baidu");
    string result = await client.GetStringAsync("/");
    return Ok(result);
}
Copy the code

The third way | typed using way

This method is the most recommended. A way of understanding and encapsulating the most personal code for those who conform.

The way programmers understand it is to define an HttpClient class that accesses third parties. It contains all the configuration information and request methods involved in this third party access. Where to use, use the constructor to construct the HttpClient, and then define the method to use.

1. Convert the logic in Case 1 to a generic class

public class BaiduHttpClient { public HttpClient _client { get; private set; } public BaiduHttpClient(HttpClient httpClient) { httpClient.BaseAddress = new Uri("http://www.baidu.com"); _client = httpClient; } public async Task<string> GetBaidu() { return await _client.GetStringAsync("/"); }}Copy the code

2. How do I register a service for this class for normal use

services.AddHttpClient<BaiduHttpClient>();
Copy the code

3. Constructor instantiation in API, call request method

private readonly BaiduHttpClient _baiduHttpClient;

public HttpClientController(BaiduHttpClient baiduHttpClient)
{
    _baiduHttpClient = baiduHttpClient;
}

[HttpGet("GetBaiduClient2")]
public async Task<ActionResult> GetBaiduClient2()
{
    string result = await _baiduHttpClient.GetBaidu();
    return Ok(result);
}
Copy the code

conclusion

In fact, generally speaking, there is no difference between these three methods, but different ways to use different scenarios. Of course, if we are a normative programmer, we should use the third way more often, of course not enough, but also understand why the third way is best, what are the advantages, that is the most important.

The resources

Official document | use in ASP.NET Core IHttpClientFactory HTTP requests

The correct posture for using HttpClient in.NET Core

The END

The end of this article, I hope to help you 😃

More exciting technical articles summary in my public number programmer tool set, continue to update, welcome to pay attention to the subscription collection.

If there are any questions or suggestions, you can exchange more original articles, writing is limited, talent and learning is shallow, if there is something wrong in the article, hope to inform.

Welfare kyi

Public account background reply: “pay attention to gift package”, get the value of 5K video learning resources

Public number background reply: “skill map”, send you a most complete developer skill map