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
asp.net asp.net-web-api2


source to share


No one has answered this question yet

Check out similar questions:

3
What is the correct way to handle global exceptions with asp.net mvc6 vnext
3
Exception handling and registration in the asp.net web api
2
Accessing the actual request in message handlers and action filters in the web API
2
POST from web API to web API unable to pass JSON object
2
SimpleInjector.ActivationException when using RegisterWebApiRequest in custom TypeFormatter
1
Bad formatter exception
0
Web API Accept XML request and navigate to another web API as JSON
0
Message: The requested resource does not support the http POST method,
0
How to put asp.net webapi parameter in body (message) instead of URI?
0
ASP.NET Web Api - Multiple Parameters Error 500



All Articles
Loading...
X
Show
Funny
Dev
Pics