This series is a collection of knowledge about ASP .NET Core. It just is my notes.
Part 12: Authentication and Authorization.
This part shows us some ways to make an HTTP request against a web service/ web api.
1. Issues when using HttpClient:
- Socket exhaustion
- DNS changes not reflecting
To get more information concerning these issues, you can read this article.
2. Solution in .NET Core is:
- use IHttpClientFactory
- Some consumption patterns:
2.1 Basic usage:
- Add HttpClient to the services container
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
// Remaining code deleted for brevity.
- Use Dependency Injection to use IHttpClientFactory.CreateClient()
public BasicUsageModel(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
....
var client = _clientFactory.CreateClient();
2.2. Named clients:
- Add HttpClient to services:
services.AddHttpClient("github", c =>
{
c.BaseAddress = new Uri("https://api.github.com/");
// Github API versioning
c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
// Github requires a user-agent
c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
});
- Create clients
var client = _clientFactory.CreateClient("github");
2.3. Typed Client:
- It's similar to create a new service class that wraps HttpClient
2.4. Generated clients: used in combination with the third party
3. Configure HttpMessageHandler
- Can be used in case you want to control the configuration of the inner HttpMessageHandler
- An example is to bypass SSL Server Certificate
- Use the extension method: ConfigurePrimaryHttpMessageHandler to create and configure
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient("configured-inner-handler")
.ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler()
{
AllowAutoRedirect = false,
UseDefaultCredentials = true
};
});
services.AddHttpClient(ONPREMISEHTTPCLIENT)
.ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = (_, __, ___, ____) => true
};
});
- Header propagation
References:
https://www.rahulpnath.com/blog/are-you-using-httpclient-in-the-right-way/



0 nhận xét:
Đăng nhận xét