Home > Software design >  How to read request content in .net ExceptionFilter
How to read request content in .net ExceptionFilter

Time:01-11

I have a legacy .Net core 3.1 web application, with a custom exception filter:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
    private readonly ILogger _logger;

    public CustomExceptionFilterAttribute(ILogger<CustomExceptionFilterAttribute> logger)
    {
        _logger = logger;
    }

    public override void OnException(ExceptionContext context)
    {
        var request = context.HttpContext.Request;
        var info = Json from request: POST, PUT, GET   Exception   etc. // <= Pseudo code
        _logger.Log(LogLevel.Critical, info);
    }
}

My requests are in JSON. When something goes wrong somewhere in the code, I want to write the content from my request to the logger.

I have tried to read from the Request.Body stream, but it's empty. I read somewhere that the buffer is deleted after is has been read for the action in the controller, but don't if it's true.

Request.Form throws an exception.

Is it possible to get the original content of the request? If yes how?

CodePudding user response:

After further research I found out:

The HttpContext.Request.Body stream is deleted by default.

To prevent deletion the following must be added to the Startup.cs file:

app.Use(next => context =>
{
    context.Request.EnableBuffering();
    return next(context);
});

The request body can then be read by:

public override void OnException(ExceptionContext context)
{
    context.HttpContext.Request.Body.Position = 0; // important
    var bodyAsText = new System.IO.StreamReader(context.HttpContext.Request.Body).ReadToEndAsync().Result;
}
  • Related