Write the body of an HTTP request when handling exceptions thrown by the MediaTypeFormatter tool that consumes the body

I have a Web Api 2.2 controller action like:

[HttpPost]
[Route("{id}")]
public void Update(int id, [FromBody] MyData data)  {}

      

HTTP clients make POST requests with the body of the message application/json

, but sometimes System.Net.Http.Formatting.JsonMediaTypeFormatter

they cannot parse the JSON that contains the body and throws an exception before the controller action is invoked.

In this case, I would like to log both exceptions where the formatter selected and the JSON text that threw the exception . I want this to happen in production (to properly account for the failure of failed requests), and so a simple "Trace" is not a viable option here. I feel like this is a pretty acceptable thing to want.

In the beginning, blush, a global error handling feature introduced with Web Api 2.1 , will be right here. But mine is System.Web.Http.ExceptionHandling.IExceptionLogger

no longer able to read the message body:

public override void OnException(HttpActionExecutedContext context)
{        string body = await context.Request.Content.ReadAsStringAsync(); // essentially
    // body is an empty string!  the formatter already consumed it, and it not available now
}

      

What options do I have for ASP.NET and / or Web Api 2 extension points to handle exceptions thrown by the MediaTypeFormatter log and which is the real request object?

+3


source to share





All Articles