Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the request body inside HttpContext from a Middleware in asp.net core 2.0

I am having a simple middleware which fetches the body of the request and store it in a string. It is reading fine the stream, but the issue is it wont call my controller which called just after I read the stream and throw the error

A non-empty request body is required

. Below is my code.

  public async Task Invoke(HttpContext httpContext)
            {
                var timer = Stopwatch.StartNew();
                ReadBodyFromHttpContext(httpContext);
                await _next(httpContext);
                timer.Stop();
            }

   private string ReadBodyFromHttpContext(HttpContext httpContext)
        {
           return await new StreamReader(httpContext.Request.Body).ReadToEndAsync();
        }
like image 778
maxspan Avatar asked Dec 04 '17 00:12

maxspan


People also ask

How do I get a request body in middleware?

Middleware { public class CreateSession { private readonly RequestDelegate _next; public CreateSession(RequestDelegate next) { this. _next = next; } public async Task Invoke(HttpContext httpContext) { //I want to get the request body here and if possible //map it to my user model and use the user model here. } }

How do I get request body in .NET Core API?

To read the request body in ASP.NET Core Web API, we will create a custom middleware. Visual Studio gives you a readymade template to create custom middleware. Right-click on your project in Solution Explorer and click “Add New Item”. In the search box type “Middleware” and you will see Middleware Class in the result.


1 Answers

You need to convert HttpContext.Request.Body from a forward only memory stream to a seekable stream, shown below.

//  Enable seeking
context.Request.EnableBuffering();
//  Read the stream as text
var bodyAsText = await new System.IO.StreamReader(context.Request.Body).ReadToEndAsync();
//  Set the position of the stream to 0 to enable rereading
context.Request.Body.Position = 0; 
like image 197
mattinsalto Avatar answered Sep 17 '22 23:09

mattinsalto