John Tseng
John Tseng

Reputation: 6352

Transform Results Of Web API Actions

How do I transform the results of my controller actions before the framework formats it?

Suppose I have a controller like:

public class Controller : System.Web.Http.ApiController {
    public object GetSomething() {
        return new { value = "something" };
    }
}

I want to be able to build something like this:

public class ActionResultFilter {
    public object InvokeAction(Action Action) {
        object ActionResult = Action.Invoke();
        if (ActionResult == null) {
            return new { value = "nothing" };
        }
        return ActionResult;
    }
}

The key things are that I want to do this after my action is executed, but before the result is converted to an HttpResponseMessage so that I don't have to handle serialization.

Here's what I've tried:

From http://www.asp.net/posters/web-api/asp.net-web-api-poster-grayscale.pdf, it looks like I want something between Controller Action and OnActionExecuted.

Upvotes: 0

Views: 299

Answers (1)

Simon Belanger
Simon Belanger

Reputation: 14870

You can get the HttpContent in HttpResponseMessage and check if it is an ObjectContent within an ActionFilterAttribute:

public class YourFilterNameAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext context)
    {
        var objectContent = context.Response.Content as ObjectContent
        if(objectContent != null && objectContent.Value == null) 
        {
            context.Response = context.Request
                                      .CreateResponse(HttpStatusCode.NotFound, 
                                                      new { value = "nothing" });
        }
    }
}

This is a minimal example (with minimal error checking and a very limited scenario) but it should get your started on the right path when it comes to intercepting and rewriting responses with action filters.

Upvotes: 3

Related Questions