Question

I'm building a RESTful API and I would like to control all possible output to my consumers. I'm implementing an ExceptionFilterAttribute to filter all exceptions raised in my controllers. This, however, doesn't give me control over errors that might happen in my application prior reaching controller code - such as routing errors. Default behaviour sends back a standard serialized HttpError giving away too much internal information to my taste, such as controller classnames etc. I would like to avoid that. What is the best way of changing this behaviour?

Was it helpful?

Solution

You can add a MessageHandler to do this. MessageHandlers run first and last in the pipeline, allowing you to process raw incoming request and raw outgoing response.

For example:

public class ErrorHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);

        if (!response.IsSuccessStatusCode)
        {
                Debug.WriteLine("something happened! - " + response.ReasonPhrase);
        }

        return response;
    }
}

And then register in your GlobalConfiguration

config.MessageHandlers.Add(new ErrorHandler());

This basically inspects the outgoing response and checks if the status code is 2xx. If not you can do something with it - log, or perhaps reset the content of the response to hide whatever you wanna hide.

OTHER TIPS

Actually, we've been very careful about not leaking internal information to remote clients by default. We will provide internal information if the request is coming from the local machine for debugging purposes, but we won't send it to remote clients. If you want to take a look at what the response might look like for a remote client, try this setting on your configuration:

config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Never;

You may also want to take a look at this blog post for more info about WebAPI's error handling:

http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx

If the defaults still don't work for you, then you should follow Filip's suggestion and just intercept the response with a message handler to send back anything you like.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top