问题
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:
They're no longer validated. Flurl now uses
TryAddWithoutValidation
under the hood, so you'll never get the "misused header name" error with theWithHeader(s)
methods. (I always found that validation behavior to be a bit overprotective.)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.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