无法设置Content-Type头部信息

16

我在设置HttpClient的Content-Type时遇到了问题。 我按照这个问题的步骤操作:How do you set the Content-Type header for an HttpClient request? 但仍然没有成功。

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 我还尝试使用Flurl库,但在尝试添加“Content-Type”时崩溃了。

misused header name content-type

那么我该如何强制它真正添加它呢? 提前感谢。

3个回答

29

我认为你应该尝试这个。

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

请查看以下链接:

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

编辑

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


1
现在,正在设置标题,这是一件好事。 但我得到了一个403错误。然而,在Postman中,请求返回json。 - timr
1
@TimRijckaert 这意味着它无法接受JSON结果。 - Ajay
1
嗯,我现在看到问题了。我的一个标头有 ""value""。所以我需要取消转义字符串。 - timr

3

更新:有关非默认内容类型,请参见新的答案

使用Flurl,像PostJsonAsync这样的方法不需要设置Content-Type为application/json。在这种情况下,这是默认的内容类型,并且它将为您设置。


2
好像我的一个参数被错误转换了,所以我会再试一次Flurl,因为它可以简化代码。谢谢。 - timr
直到你遇到一个需要在POST请求中设置Content-Type头的API :-/ - quentin-starin
@qes,你是在说你正在发布JSON格式的数据,但API要求你设置一个Content-Type而不是application/json吗? - Todd Menier
@ToddMenier 这是一个用于航班数据的SOAP XML API,我必须将其设置为text/xml,同时在post请求中添加XML请求正文,否则API会返回415错误。我可能错过了一些细节,但我无法找出如何让Flurl实现这一点。然而,Ajay上面提供的使用HttpClient的解决方案对我很有帮助。 - quentin-starin
@qes 你在 Flurl 调用中尝试过 .WithHeader("Content-Type", "text/xml") 吗? - Todd Menier
1
@ToddMenier 是的,它会导致无效操作异常:误用的标头名称。请确保请求标头与 HttpRequestMessage 一起使用,响应标头与 HttpResponseMessage 一起使用,内容标头与 HttpContent 对象一起使用。这来自于 System.Net.Http.Headers.HttpHeaders.Add(...)。 - quentin-starin

2
最新且最好的使用Flurl进行操作的方法是升级到2.0版本。2.0版本在头部方面引入了多项增强功能:
  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", ... }
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接