There is a similar SO question here which talks about the performance of HttpClient
objects and recommends to use one HttpClient
instance per appli
You can:
Docs: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.1
Here you create one client instance and add headers that will be applied to all requests.
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Content-Type", contentTypeValue);
In this dotnet core 2.1 example, we register a preconfigured named instance:
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");
});
If your headers belong to a single request only, simple set them per request.
var client = new HttpClient();
var request = new HttpRequestMessage();
request.Headers.Add("Content-Type", "text/plain");
var response = await client.SendAsync(request);
Using this approach you can use a shared HttpClient
instance.
If you want a new "clean" HttpClient instance, the recommended approach for asp.net core is to inject IHttpClientFactory
and use _clientFactory.CreateClient()
.
public class MyService {
public MyService (IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async Task DoSomething()
{
var client = _clientFactory.CreateClient();
// do request
}
}