1

Motivated by this: Google JSON Style Guide, I want to insert a bit of custom serialization logic to my rest API. I'm using the WebAPI 2 and JSON.NET. My goal is to wrap the 'payload' of my response in the 'data' field of the main JSON response, as described in the style guide, include an apiVersion field in every response, and that sort of thing. Of course the controller actions just return straight POCO's, and I want to modify the container that they're sent inside of, not the POCOs themselves, so:

{
  "id": "111",
  "apiVersion": "1.0",
  "data": {
    "kind": "monkey",
    "name": "manny",
    "age": "3"
  },
  "error": null
}

...that type of thing. So I envision inserting little bits of standard data into every response before it goes over the wire. What's the best way to accomplish this?

TIA.

1 Answer 1

5

I believe you can use an ActionFilterAttribute to achieve this kind of behaviour. You would first need to create a class to represent your wrapped response (all the properties are string, adjust as you need):

public class WrappedJsonResponse
{
    public string Id {get;set;}
    public string ApiVersion {get;set;}
    public object Data {get;set;}
    public string Error {get;set;}
}

The ActionFilterAttribute allow you to do some processing after the execution of an action via the virtual OnActionExecuted method:

public class WrappedJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext context)
    {
        // A POCO response will normally be wrapped in an ObjectContent
        var content = context.Response.Content as ObjectContent

        if(content != null)
        {
            // Create the WrappedJsonResponse object appropriately and
            // put the original result in the Data property
            content.Value = new WrappedJsonResponse { Data = content.Value };
            content.ObjectType = typeof(WrappedJsonResponse);
        }
    }
}

With the attribute, you can then choose to apply it where you want (whole controller, action only or as a default filter).

Note: I do not have access to a development environment at the moment and have not tested the filter. If this is not complete, it should at least give you an idea on how it can be done.

Sign up to request clarification or add additional context in comments.

1 Comment

That's got it. for an off-the-cuff solution, it was right on the mark! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.