Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I not exclude charset in Content-Type when using HttpClient?

I am attempting to use HttpClient in a .net core project to make a GET request to a REST service that accepts/returns JSON. I don't control the external service.

No matter how I try, I can't figure out to set the Content-Type header to application/json only.

When I use

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

it sends in the HTTP GET request:

Content-Type: application/json; charset=utf-8

However, this particular service does not work with this. It will only work if the header is:

Content-Type: application/json

I've tried setting headers without validation, and all the approaches I've found on the web/SO doesn't apply to .net core. All the other the approaches to sending HTTP requests aren't available in .net core, so I need to figure this out. How can I exclude the charset in content-type?

EDIT with workaround

As mentioned in the answers, the service should be using the Accept header. The workaround (as Shaun Luttin has in his answer) is to add an empty content to the GET (what? GETs don't have content! yeah...). It's not pretty, but it does work.

like image 782
Erick T Avatar asked Dec 19 '22 12:12

Erick T


1 Answers

You're setting the Accept header. You need to set the ContentType header instead, which is only canonical for a POST.

var client = new HttpClient();
var content = new StringContent("myJson");
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var result = client.PostAsync("http://bigfont.ca", content).Result;

If you really want to set it for a GET, you can do this:

var client = new HttpClient();
var message = new HttpRequestMessage(HttpMethod.Get, "http://www.bigfont.ca");
message.Content = new StringContent(string.Empty);
message.Content.Headers.Clear();
message.Content.Headers.Add("Content-Type", "application/json");
var result = client.SendAsync(message).Result;
like image 101
Shaun Luttin Avatar answered Dec 24 '22 02:12

Shaun Luttin