I am probably missing something really simple but I just cannot find it.
An API I am working with demands the inclusion of a Content-Type header even with GETs.
I am struggling to add the header to my request.
Here is the code that builds the httpclient:
public static async Task<HttpClient> Authenticate(string baseUrl, string clientId, string clientSecret)
{
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
string toBeHashed = $"client_id={clientId}&client_secret={clientSecret}";
string hashed = sha256_hash(toBeHashed);
AuthRequest request = new AuthRequest
{
client_id = clientId,
hash = hashed
};
StringContentWithoutCharset body = new StringContentWithoutCharset(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync($"{baseUrl}authenticate", body);
AuthResponse result = await JsonSerializer.DeserializeAsync<AuthResponse>(await response.Content.ReadAsStreamAsync());
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.data.token);
return httpClient;
}
And here is 2 different attempts at making a GET call.
When I look in Fiddler the Content-Type is missing from the headers:
public class Functions
{
private HttpClient _httpClient;
private readonly string _baseUrl;
public Functions(string baseUrl, string clientId, string clientSecret)
{
_httpClient = Helpers.Authenticate(baseUrl, clientId, clientSecret).Result;
_baseUrl = baseUrl;
}
public async Task ProductList()
{
// this doesn't work
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"{_baseUrl}products");
request.Headers.TryAddWithoutValidation("Content-Type", "application/json");
HttpResponseMessage response1 = await _httpClient.SendAsync(request);
ProductList result1 = await JsonSerializer.DeserializeAsync<ProductList>(await response1.Content.ReadAsStreamAsync());
// nor does this
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
HttpResponseMessage response = await _httpClient.GetAsync($"{_baseUrl}products");
ProductList result2 = await JsonSerializer.DeserializeAsync<ProductList>(await response.Content.ReadAsStreamAsync());
}
}
Any help would be greatly appreciated.