尝试读取Core 2.1 HttpRequest.Body为空

时间:2018-11-20 07:09:17

标签: asp.net-core asp.net-core-mvc httpwebrequest asp.net-core-webapi asp.net-core-2.1

我正在尝试从HttpRequest.Body读取流数据,但是我得到的是空字符串。 请求是从.net项目发送到这里的

        HttpWebRequest request = null;
        Uri uri = new Uri(**Endpoint**);
        UTF8Encoding encoding = new UTF8Encoding();
        byte[] bytes = encoding.GetBytes(message);
        request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = bytes.Length;
        request.UseDefaultCredentials = true;
        using (Stream writeStream = request.GetRequestStream()) {
            writeStream.Write(bytes, 0, bytes.Length);
        }
        try {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK) {
                return true;
            } else {
                return false;
            }
        } catch {
            lock (endpointLock) {
                _pushHttpEndpoint = null;
            }
            return false;
        }

请求发送到此处。这是.net core 2.1应用程序。我正在尝试读取请求正文中的数据,但返回的是空

    [HttpPost]
    public string Post()
    {
        var bodyStr = "";
        var req = HttpContext.Request;           
        req.EnableRewind();            
        using (StreamReader reader
                  = new StreamReader(req.Body, Encoding.UTF8, true, 1024, true))
        {
            bodyStr = reader.ReadToEnd();
        }    

        req.Body.Seek(0, SeekOrigin.Begin);
        //do other stuff
        return bodyStr;
     }

有人可以帮我这个忙吗? 我们处于无法更改.net解决方案代码的位置。任何更改都应在.net核心解决方案端进行。我们正在尝试将新的api替换现有的Endpoint。 :(

3 个答案:

答案 0 :(得分:1)

您的类型是“类型是application / x-www-form-urlencoded”,因此请使用[FromForm]属性。以下代码供您参考:

.Net项目:

        HttpWebRequest request = null;
        Uri uri = new Uri("https://localhost:44365/Home/Post");
        UTF8Encoding encoding = new UTF8Encoding();
        var postData = "thing1=hello";
        postData += "&thing2=world";
        byte[] bytes = encoding.GetBytes(postData);
        request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = bytes.Length;
        request.UseDefaultCredentials = true;
        using (Stream writeStream = request.GetRequestStream())
        {
            writeStream.Write(bytes, 0, bytes.Length);
        }
        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                //return true;
            }
            else
            {
               // return false;
            }
        }
        catch(Exception e)
        {

        }

在您的.net核心项目上:

    [HttpPost]
    public string Post([FromForm]AcceptValue acceptValue)
    {

        //do other stuff
        return "";
    }

    public class AcceptValue {
        public string thing1 { get; set; }

        public string thing2 { get; set; }
    }

Result :

答案 1 :(得分:1)

首先,我知道问题是关于ASP.NET Core 2.1的,但是我在2.2上也遇到了同样的问题。

这是我解决的方法:

在ASP.NET Core 2.2中启用此功能的方法如下:

首先在请求管道级别启用缓冲。这是在Startup.cs类中完成的。

const result = [{ PRODUCT_ID: 87 }];
console.log(result[0].PRODUCT_ID);

第二步:

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {

    // Configure the HTTP request pipeline.
    app.Use(async (context, next) =>
    {
      //enable buffering of the request

      context.Request.EnableBuffering();

      await next();

    });
  }

答案 2 :(得分:-1)

您应该使用[FromBody]属性。

就是这样:

[HttpPost]
public string Post([FromBody] object body) {
// do stuff here
}