繁体   English   中英

如何更改HttpContent的标题

[英]How to change the a Header of HttpContent

我有这段代码可以将我的内容的标题从{text/plain; charset=utf-8} {text/plain; charset=utf-8}改为"{application/json}"

using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
{
    string content = "some json data";
    System.Net.Http.StringContent sc = new System.Net.Http.StringContent(content);
    sc.Headers.Remove("Content-Type"); // "{text/plain; charset=utf-8}"
    sc.Headers.Add("Content-Type", "application/json");
    System.Net.Http.HttpResponseMessage response = client.PostAsync("http://foo.bar", sc).Result;
}

有没有一种方法可以直接修改它,而不是删除并添加它?

使用StringContent此重载来设置内容类型

sc = new StringContent(content, Encoding.UTF8, "application/json");

此后,您无需添加/删除标题值。

如果您通过序列化一些数据手动构建json字符串,那么还有更好的方法。 您可以使用PostAsJsonAsync扩展方法:

using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
{
    var response = await client.PostAsJsonAsync("http://foo.bar", data);
}

它将自动执行以下操作

  • 将数据序列化为JSON
  • 创建StringContent
  • 提供正确的应用程序/ json媒体类型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM