Asp.Net WebRequest Get请求如何将参数放入信息体body中,如下图Fiddler抓包所示。
直接get请求,调用request.GetRequestStream()时会出错
Asp.Net WebRequest Get请求如何将参数放入信息体body中,如下图Fiddler抓包所示。
直接get请求,调用request.GetRequestStream()时会出错
可以使用反射来设置ContentBodyNotAllowed实现,示例代码如下
using System.Net;
using System.IO;
using System.Reflection;
namespace Test.Controllers
{
public class HomeController : Controller
{
public ActionResult test() {
var request = WebRequest.Create("http://www.w3dev.cn");
request.ContentType = "application/json";
request.Method = "GET";
request.ServicePoint.Expect100Continue = false;//取消Expect:100-continue请求头,要不服务器没有正确处理会报错,如IIS。远程服务器返回错误: (417) Expectation Failed。
var type = request.GetType();
var currentMethod = type.GetProperty("CurrentMethod", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(request);
var methodType = currentMethod.GetType();
methodType.GetField("ContentBodyNotAllowed", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(currentMethod, false);
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write("{fid:123}");
}
var response = (HttpWebResponse)request.GetResponse();
return Content("");
}
}