2
votes

I upgraded my app to .net Core 3.1 And when I try to send a Post request by a http client to my web App The body of the message arrives empty at the destination. when i was checking the Request in my web App, i saw that the Request.ContentLenght value is completely correct.

I realized that there are problems with this in .net core 3.1, Does anyone have a solution to this problem?

  • i thought it may be a Buffering issue, but i didn't find implementaion of EnableBuffering() method.

Here is my code:

Http Client who makes a post request for a web app:

StringContent httpContent = new StringContent("test Data");
httpContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");

var response =  await myHttpClient.PostAsync(destUrl,httpContent);

Implementing a Post Request in My Web App:

[HttpPost]
public async Task<IActionResult> Post()
{
    // Request.Body is empty.
}
1
Please check if you have already read request body in filter/middleware etc - Fei Han

1 Answers

2
votes

If you are receiving an empty string, it means that something else already read it. Since Request.Body is a stream, you have to seek to the beginning to read it again.

But first you need to call EnableBufferring(), because by default Request.Body can only be read only once. You can do it Startup.cs file:

public void Configure(IApplicationBuilder app)
{
    // be sure to add it before the other middleware
    app.Use((context, next) =>
    {
         context.Request.EnableBuffering();
         return next();
    });

    // everything else
}

Then you can read your Request.Body:

[HttpPost]
public async Task<IActionResult> Post()
{
    using var reader = new StreamReader(Request.Body);
    reader.BaseStream.Seek(0, SeekOrigin.Begin); 
    var rawMessage = await reader.ReadToEndAsync();
}