The first part of your question: is there a difference for adding headers?
HttpClient client = HttpClientFactory.Create(handler);
Method 1:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Method 2:
var headers = new Dictionary<string, string>{{"Accept", "application/json"}};
headers.ForEach(h => client.DefaultRequestHeaders.Add(h.Key, h.Value));
Method 1 gives you good strongly typed values with the ability to add multiple accept types. In method 2, there is another “magic line” that can be a place for typos, and there is no way to add several types of adoption.
2 : ?
HttpClient . , . , , . , HttpClient , . , . , DefaultRequestHeaders, factory.
public class ApiService
{
public static HttpClient GetClient()
{
var client = new HttpClient(new Uri("https://someservice/"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
}
:
public async Task DoStuff()
{
using(var client = ApiService.GetClient())
{
var data = await client.GetAsync<dynamic>("Sales");
var data2 = await client.GetAsync<dynamic>("Products");
}
}
HttpClients using. , .