Search code examples
c#asp.net-web-api2httpcontext

How to read JSON body in HttpActionExecutedContext in case of exception


We are using Web API 2 and to handle exception we have create a custom attribute by inheriting the ExceptionFilterAttribute. Now we want to save the logs of JSON request to database in case of exception .

I tried to read using context.Request.Content.ReadAsStringAsync().Result but its returning empty string.

Please help!!


Solution

  • You can reset request stream position and reread it:

    class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override async Task OnExceptionAsync(HttpActionExecutedContext context, CancellationToken cancellationToken)
        {
            var stream = await context.Request.Content.ReadAsStreamAsync();
            stream.Position = 0;
            using (var reader = new StreamReader(stream))
            {
                var requestString = reader.ReadToEnd();
            }
        }
    }