When working with ASP.Net Web API, it is important to return a consistent response for all the requests that are processed by your API regardless of success or failure. This makes it a lot easier to consume the API, without requiring complex code on the client. By using a custom wrapper for Web API responses, you can ensure that all of your responses have a consistent structure, and you can also include custom metadata. This article presents a discussion on how we can decorate Web API responses with useful information.

Let’s understand the problem we are trying to solve. In essence, your standard Web API response will vary when executing different action methods, and we need a way to get around the inconsistency of these responses. When you are trying to retrieve data using HTTP GET, the response may contain data for one or more records. When you are executing a HTTP POST, the response may not even include a body, but only a header. And when there is an error when executing the request, the API will return an object with the appropriate error message.

The differences among all of these responses make it difficult to consume the API, because the consumer needs to know the type and structure of the data that is being returned in each case. Both the client code and the service code become difficult to manage.

Now that we know what the problem is all about, let’s examine the two ways to overcome the problem in Web API. One of the options is to use a message handler. The other option is to intercept the call using a filter and override the OnActionExecuted method. We would prefer to use a message handler because it is called earlier in the request processing pipeline. (Incidentally, you can take advantage of message handlers to process a request even before it reaches the HttpControllerDispatcher.) So, let’s implement a custom message handler to wrap the response by extending the DelegatingHandler class. This will provide a way to send out responses from the Web API in a consistent manner.