Home > other >  .Net 6 API save request and reponse log in database
.Net 6 API save request and reponse log in database

Time:12-25

I need to save my request and response JSON in database and so far after i didn't find any code to do so.

In older .net core version i used below code to read body :

context.Request.EnableRewind();

But it seems this code not working in .Net 6 or i don't know the trick to use it, Here it is my last code which is able to read response but request is always empty.

public class APILogFilter : IActionFilter
{
    public async void OnActionExecuted(ActionExecutedContext context)
    {
        string RequestBody = "";
        context.HttpContext.Request.EnableBuffering();
        using (StreamReader reader = new StreamReader(context.HttpContext.Request.Body, Encoding.UTF8, true, 1024, true))
        {
            RequestBody = await reader.ReadToEndAsync();
        };

        string ResultBody = "";
        if (context.Result is ObjectResult)
        {
            var objResult = (ObjectResult)context.Result;
            ResultBody = HelperConvert.GetJSONSerialize(objResult.Value);
        }
        //Save request and response in database 
    }
    public void OnActionExecuting(ActionExecutingContext context)
    {

    }
}

I hope someone can help me out.

CodePudding user response:

I can offer you to use Middleware instead of filter.

This middleware works good on .NET 6.

public class BodyLoggerMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<BodyLoggerMiddleware> _logger;

    public BodyLoggerMiddleware(RequestDelegate next, ILogger<BodyLoggerMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        
        try
        {
            string requestBody;
            context.Request.EnableBuffering();
            using (StreamReader reader = new StreamReader(context.Request.Body, Encoding.UTF8, true, 1024, true))
            {
                requestBody = await reader.ReadToEndAsync();
            }
            _logger.LogInformation("Request: {Request}", requestBody);
        }
        finally
        {
            context.Request.Body.Position = 0;
        }
       

        Stream originalBody = context.Response.Body;

        try
        {
            using (var memStream = new MemoryStream())
            {
                context.Response.Body = memStream;

                await _next(context);

                memStream.Position = 0;
                string responseBody = new StreamReader(memStream).ReadToEnd();
                _logger.LogInformation("Response: {Response}", responseBody);
                memStream.Position = 0;
                await memStream.CopyToAsync(originalBody);
            }
        }
        finally
        {
            context.Response.Body = originalBody;
        }
    }
}
  • Related