如何正确设置HttpWebRequest的ContentType属性?解决请求头缺失问题
解决HttpWebRequest POST请求中Content-Type请求头丢失的问题
我在使用HttpWebRequest编写POST请求时遇到了一个棘手的问题:明明通过专属属性设置了ContentType = "application/json",但请求始终返回400 Bad Request,用Fiddler抓包发现Content-Type请求头根本没被带上,而相同参数在Postman里完全正常。
一开始我的代码是这样写的:
HttpWebRequest httpWebRequest = (HttpWebRequest)webRequest; httpWebRequest.Method = "POST"; httpWebRequest.KeepAlive = false; httpWebRequest.ServicePoint.Expect100Continue = false; httpWebRequest.ContentType = "application/json";
接着设置请求体:
using (StreamWriter streamWriter = new StreamWriter(streamWebRequest)) { streamWriter.Write(sJson); }
最后发送请求:
WebResponse webResponse = httpWebRequest.GetResponse();
排查了很久都没找到原因,多次尝试后发现,只要把设置ContentType的代码移到写入请求体的代码块之后,Content-Type请求头就正常出现在请求里了,请求也能成功返回。
调整后的核心代码顺序:
// 先初始化请求并写入请求体 HttpWebRequest httpWebRequest = (HttpWebRequest)webRequest; httpWebRequest.Method = "POST"; httpWebRequest.KeepAlive = false; httpWebRequest.ServicePoint.Expect100Continue = false; using (StreamWriter streamWriter = new StreamWriter(streamWebRequest)) { streamWriter.Write(sJson); } // 后设置ContentType httpWebRequest.ContentType = "application/json"; WebResponse webResponse = httpWebRequest.GetResponse();
这里需要注意两个关键点:
- HttpWebRequest中像ContentType这类有专属属性的请求头,不能通过Headers集合设置,必须使用对应的专属属性
- 设置Content-Type的操作要放在写入请求体之后,否则该请求头不会被正确加入到请求中
内容的提问来源于stack exchange,提问作者Alexey Nagoga
相关产品推荐
相关产品推荐

