I am trying to make a GET request in C# and need to set the Content-Type header to application/json and set a header with my api key. I have tried searching but surprisingly have not found a straightforward way to do this.
This answer is very close to what I want, because they are able to set the Content-Type header here, but I also need to set a custom header for my api key and StringContent does not have additional fields for such a thing.
request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",
Encoding.UTF8,
"application/json");//CONTENT-TYPE header
^ their answer, for reference. This is my code, but I get a null result. I know that I can hit the api in postman with these values, but I am assuming the way I configure my HttpRequestMessage is wrong so the request fails.
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Get
};
// need Content to be not null, this seems wrong
request.Content = new StringContent("");
// need to set Content-Type to application/json
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// set api-key header
request.Content.Headers.Add("api-key", apiAdminKey);
request.RequestUri = new Uri($"{URL}?id={id}");
return client.SendAsync(request, HttpCompletionOption.ResponseContentRead);
Any advice?
Update
Got it working with just HttpClient, for some reason I thought I could not set the headers using client.DefaultRequestHeaders.Add.
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("api-key", apiAdminKey);
return client.GetAsync($"{URL}?id={id}");
Thanks for the help!!!!