net core 5 middleware read request body code example

Example: c# core middleware request.body

public class RequestApplicationLogMiddleware
{
  private readonly RequestDelegate _next;
  //custom logic
  private WebApiTemplate.Interface.ISession _session;


  public RequestApplicationLogMiddleware(RequestDelegate next, WebApiTemplate.Interface.ISession session)
  {
    //custom logic
    this._session=session;
    this._next = next;
  }


  public async Task InvokeAsync(HttpContext context, IApplicationLog log)
  {
    //custom logic
    _session.Id=Guid.NewGuid().ToString();
    //custom logic
    if (context.Request.Path.Value.Contains("api"))
    {
      var bodyStr = "";
      var req = context.Request;

      // Allows using several time the stream in ASP.Net Core
      req.EnableRewind();

      // Arguments: Stream, Encoding, detect encoding, buffer size 
      // AND, the most important: keep stream opened
      using (StreamReader reader
             = new StreamReader(req.Body, Encoding.UTF8, true, 1024, true))
      {
        bodyStr = reader.ReadToEnd();
      }

      // Rewind, so the core is not lost when it looks the body for the request
      req.Body.Position = 0;
	  //custom logic
      log.SaveRqst(new { Header = context.Request.Headers, Data = bodyStr }, context.Request.Path);
    }
    await _next(context);
  }
}