Asp.Net WebRequest Get请求如何将参数放入信息体body中

Asp.Net WebRequest Get请求如何将参数放入信息体body中,如下图Fiddler抓包所示。

img

直接get请求,调用request.GetRequestStream()时会出错

img

可以使用反射来设置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("");
        }
}

代码来源:https://stackoverflow.com/questions/43421126/how-to-use-httpclient-to-send-content-in-body-of-get-request

post请求的参数内容才放在body中。
get请求的参数是在请求头中。

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632