How do I not exclude charset in Content-Type when

2019-07-04 13:23发布

问题:

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.

回答1:

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;


回答2:

If you are the client and you perform a GET request how can you specify the Content-Type? Isn't it supposed to say what your are able to Accept ? According to this 7.2.1 Type you can only set Content-Type when there is Body.