0

I have a Middleware that logs the request information in my ASP.Net core API project, but the proble is when I read the request in the middleware, I can't read the same request in my Controller.

Who can I read the Json request in my Middleware and in my Controller?

Middleware Comtroller

using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using srpago_oxxo.Library.Logger;
using srpago_oxxo.Library.Logger.Handlers;
using srpago_oxxo.Library.Logger.Formatters;
using Microsoft.AspNetCore.Http.Internal;

namespace srpago_oxxo.Middlewares
{
    public class IOMiddleware
    {
        private readonly RequestDelegate _next;
        private Logger logger;

        public IOMiddleware(RequestDelegate next)
        {
            _next = next;

            logger = new Logger("SRPAGO-OXXO");
            var formatter = new WebFormatter();
            var handler = new StdoutHandler();
            handler.SetFormatter(formatter);

            logger.AddHandler(handler);
        }

        public async Task Invoke(HttpContext context)
        {
            var contentLenth = context.Request.ContentLength.ToString();
            contentLenth = contentLenth == "" ? "-" : contentLenth;

            var info = new Dictionary<string, string>()
            {
                {"{code}", "200"},
                {"{clientIp}", context.User.ToString()},
                {"{method}", context.Request.Method},
                {"{path}", context.Request.Path.Value},
                {"{bodyLength}", contentLenth},
                {"{message}", await GetJsonRequest(context)},
            };

            logger.Info(info);

            await _next.Invoke(context);
        }

        private async Task<string> GetJsonRequest(HttpContext context)
        {
            var body = context.Request.Body;
            context.Request.EnableRewind();

            var request = context.Request;

            var buffer = new byte[Convert.ToInt32(request.ContentLength)];
            await request.Body.ReadAsync(buffer, 0, buffer.Length);

            var bodyAsText = Encoding.UTF8.GetString(buffer);
            request.Body = body;

            if (bodyAsText == "")
            {
                bodyAsText = "{}";
            }

            return bodyAsText;
        }
    }
}

This is my Base Controller

using System.IO;
using Microsoft.AspNetCore.Mvc;

namespace srpago_oxxo.Controllers
{
    public class BaseController : Controller
    {

        protected string GetJsonRequest()
        {
            var request = this.HttpContext.Request;
            var stream = new StreamReader(request.Body);
            var body = stream.ReadToEnd()
                .Replace("\n", "")
                .Replace("\t", "");

            return body;
        }
    }
}

When I use the function GetJsonRequest after the IOMiddleware logs the request data, it does'nt return any data at all.

Can you help me whit this problem?

  • Read the body and copy it into another stream and pass it down the pipeline. – Nkosi May 30 '18 at 22:53
  • Read the original answer here and see if it applies to the current situation https://stackoverflow.com/a/43404745/5233410 – Nkosi May 30 '18 at 23:09

0 Answers0