Response formatting needs to pushed into the message handler pipeline to enable handling/logging of serialization errors.

Topics: ASP.NET Web API
Sep 11, 2012 at 11:16 AM
Edited Sep 12, 2012 at 1:01 PM

Copied this to an issue here: as it's requesting a change to the pipeline and is therefore an issue.

I've implemented a standard logging functionality in a web API.

The primary hook for this is a DelegatingHandler which captures the request and response, assigns a request ID etc.

I'm not interested in logging the request and response bodies - just high level URL and headers from the request, and status code & description from the response; and also any exception that occurs if the response is a 500 or other exception.

One major issue I found when implementing this in a delegating handler was that if an error occurred during JSON or XML serialization, the client would receive a 500 response; but I would log a 200.  The reason?  At that point in the request pipeline - content serialization has not occurred, as it's not triggered until the HttpControllerHandler has executed the whole handler pipeline in the first place.

The only way I found to actually capture the 'real' 500 response was to push the logging call out to an HttpModule to examine the actual Asp.Net HttpResponse; which to me seemed a bit of a hack (especially since it won't work if I move to self-host).

Even then, however, I still was unable to capture the actual exception - even with a global exception filter enabled.

So the situation I have is that if a client (or indeed my QA team) reports a server error on an operation, that is caused by a problem with content serialization (which is happening a lot at the moment as I get all my DataContracts and implementations straight), there is no way to capture that and log it.

For a more in depth technical look at the overall issue please see this Stack Overflow ( Q&A.  In it I propose that the only way at the moment to deal with this situation is to lift all the HttpControllerHandler code out of the source, including it's internal dependencies, and rewrite it - which I don't fancy.