Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't set Content-Type header

I'm having trouble setting the Content-Type on HttpClient. I followed along this question: How do you set the Content-Type header for an HttpClient request? But still no luck.

String rcString = JsonConvert.SerializeObject(new RoadsmartChecks() { userguid = user_guid, coords = coordinates, radius = (radius * 100) + "" }, ROADSMART_JSON_FORMAT, JSONNET_SETTINGS);
HttpClient c = new HttpClient();
c.BaseAddress = new Uri(BASE_URL);
c.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json"); //Keeps returning false
c.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", hash_aes);
c.DefaultRequestHeaders.TryAddWithoutValidation("Roadsmart-app", Constant.APP_ID);
c.DefaultRequestHeaders.TryAddWithoutValidation("Roadsmart-user", user_guid);
c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, BASE_URL + URL_CHECKS + "/fetch");
req.Content = new StringContent(rcString);
await c.SendAsync(req).ContinueWith(respTask =>
{
    Debug.WriteLine("Response: {0}", respTask.Result);
});

Debugger I also tried by using the Flurl library, but it crashes when trying to add the 'Content-Type'.

misused header name content-type

So how can I force it so it really adds it? Thanks in advance.

like image 992
timr Avatar asked Mar 04 '15 09:03

timr


2 Answers

I think you should try this

req.Content = new StringContent(rcString, Encoding.UTF8, "application/json");

checkout this links :

How do you set the Content-Type header for an HttpClient request?

Edit

Remove this line c.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json"); and check

like image 166
Ajay Avatar answered Sep 21 '22 22:09

Ajay


UPDATE: See new answer for non-default content types

With Flurl you shouldn't need to set Content-Type to application/json for methods like PostJsonAsync. This is the default content type in this case and it will get set for you.

like image 21
Todd Menier Avatar answered Sep 23 '22 22:09

Todd Menier