Can't set Content-Type header

半世苍凉 提交于 2019-12-08 16:03:12

问题


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);
});

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.


回答1:


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




回答2:


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.




回答3:


The latest and greatest answer to this with Flurl is to upgrade. 2.0 introduces several enhancements in the headers dept:

  1. They're no longer validated. Flurl now uses TryAddWithoutValidation under the hood, so you'll never get the "misused header name" error with the WithHeader(s) methods. (I always found that validation behavior to be a bit overprotective.)

  2. In a fluent call they're set at the individual request level rather than the FlurlClient level, so you won't run into concurrency issues when reusing the client.

  3. Since hyphens are common in header names but not allowed in C# identifiers, there's a new convention where underscores are converted to hyphens so you don't have to give up object notation when specifying multiple:

    url.WithHeaders(new { Content_Type = "foo", ... }
    


来源:https://stackoverflow.com/questions/28851125/cant-set-content-type-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!