In ASP.NET Core I typically avoid to use the HttpClientFactory directly but instead I use the named or typed httpclients.
You can configure the client using the AddHttpClient method(in case of named clients):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
}); |
or inside the constructur (in case of typed clients):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class GitHubService | |
{ | |
public HttpClient Client { get; } | |
public GitHubService(HttpClient client) | |
{ | |
client.BaseAddress = new Uri("https://api.github.com/"); | |
// GitHub API versioning | |
client.DefaultRequestHeaders.Add("Accept", | |
"application/vnd.github.v3+json"); | |
// GitHub requires a user-agent | |
client.DefaultRequestHeaders.Add("User-Agent", | |
"HttpClientFactory-Sample"); | |
Client = client; | |
} | |
} |
This provides proper encapsulation and isolation of the configuration of each httpclient.
But what if you want more control on the HttpClient behavior? For example, you want to disable AutoRedirect on the HttpClient. That is not possible through the configuration above.
In that case you can use the ConfigurePrimaryHttpMessageHandler extension method.
For a named client:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddHttpClient("github") | |
.ConfigurePrimaryHttpMessageHandler(() => | |
{ | |
return new HttpClientHandler() | |
{ | |
AllowAutoRedirect = false, | |
}; | |
}); | |
} |
For a typed client:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddHttpClient<GithubService>() | |
.ConfigurePrimaryHttpMessageHandler(() => | |
{ | |
return new HttpClientHandler() | |
{ | |
AllowAutoRedirect = false, | |
}; | |
}); | |
} |