无法设置Content-Type标头 [英] Can't set Content-Type header

查看:630
本文介绍了无法设置Content-Type标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在HttpClient上设置Content-Type. 我遵循了这个问题:如何做您为HttpClient请求设置了Content-Type标头? 但是仍然没有运气.

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

我也尝试使用Flurl库,但是在尝试添加"Content-Type"时崩溃.

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.

推荐答案

我认为您应该尝试此

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

签出此链接:

如何设置HttpClient请求的Content-Type标头?

删除此行c.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");并检查

这篇关于无法设置Content-Type标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆