HttpWebRequest.GetRequestStream避免ProtocolViolationException

时间:2017-05-26 06:11:35

标签: c# asp.net-mvc asp.net-web-api httpwebrequest

当方法为HttpWebRequest.GetRequestStream时,有没有办法阻止GET抛出异常?

我知道HEADGET不应包含有效HTTP中的正文,但有些服务器无论如何都会接受这些方法的正文(例如,Elasticsearch的搜索功能)。我必须调用一些get API方法来从请求体中检索参数。

var uri = new Uri(@"someurl");
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.Accept = "*/*";
request.ContentType = "application/json";

var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(JsonConvert.SerializeObject(someObject));
request.ContentLength = bytes.Length;

using (var writeStream = request.GetRequestStream())
{
    writeStream.Write(bytes, 0, bytes.Length);
}

0 个答案:

没有答案