[英]How to change the a Header of HttpContent
I have this code to change the Header of my content from {text/plain; charset=utf-8}
我有这段代码可以将我的内容的标题从{text/plain; charset=utf-8}
{text/plain; charset=utf-8}
to "{application/json}"
{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;
}
Is there a way to modify it directly instead of removin and adding it? 有没有一种方法可以直接修改它,而不是删除并添加它?
Use this overload of StringContent
for setting content-type 使用StringContent
此重载来设置内容类型
sc = new StringContent(content, Encoding.UTF8, "application/json");
After this, you don't need to add/remove header values. 此后,您无需添加/删除标题值。
If you are building json string manuallly by serializing some data, then there is much better way. 如果您通过序列化一些数据手动构建json字符串,那么还有更好的方法。 You can use PostAsJsonAsync
extension method: 您可以使用PostAsJsonAsync
扩展方法:
using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
{
var response = await client.PostAsJsonAsync("http://foo.bar", data);
}
It will automatically do following things 它将自动执行以下操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.