Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core 2.1 HttpRequest.Body is empty when trying to read it

I am trying to read stream data from HttpRequest.Body but I am getting empty string. The request is send here from .net project

        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;
        }

The request is send here.This is .net core 2.1 application. I am trying to read the data in request body but that is returning empty

    [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;
     }

Can someone please help me with this. We are in position where we cannot change the .net solution code. Any changes should be done in .net core solution side. We are trying to fit the new api in place of existing Endpoint. :(

like image 228
Phoebe Buffay Avatar asked Nov 20 '18 07:11

Phoebe Buffay


2 Answers

First I know the question is asking about ASP.NET Core 2.1 but I had the same problem on 2.2.

This is how I solved it:

The way to enable this in ASP.NET Core 2.2 is the following:

First enable Buffering at the request pipeline level. This is done in the Startup.cs class.

  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();

    });
  }

Second inside your action:

  Request.EnableRewind();
  Request.Body.Seek(0, SeekOrigin.Begin);

  using (var reader = new StreamReader(Request.Body, Encoding.ASCII))
  {
    var requestBody = reader.ReadToEnd();
    // Reset the stream just in case it is needed further down the execution pipeline       
    Request.Body.Seek(0, SeekOrigin.Begin);
  }
like image 194
Jonathan Alfaro Avatar answered Nov 15 '22 08:11

Jonathan Alfaro


Your type is "type is application/x-www-form-urlencoded" , so use [FromForm] attribute . Code below is for your reference :

.Net project :

        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)
        {

        }

On your .net Core Project :

    [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 :

like image 35
Nan Yu Avatar answered Nov 15 '22 09:11

Nan Yu