Add 'standard' JSON fields to serialized objects in REST API -


motivated this: google json style guide, want insert bit of custom serialization logic rest api. i'm using webapi 2 , json.net. goal wrap 'payload' of response in 'data' field of main json response, described in style guide, include apiversion field in every response, , sort of thing. of course controller actions return straight poco's, , want modify container they're sent inside of, not pocos themselves, so:

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

...that type of thing. envision inserting little bits of standard data every response before goes on wire. what's best way accomplish this?

tia.

i believe can use actionfilterattribute achieve kind of behaviour. first need create class represent wrapped response (all properties string, adjust 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 processing after execution of action via virtual onactionexecuted method:

public class wrappedjsonattribute : actionfilterattribute {     public override void onactionexecuted(httpactionexecutedcontext context)     {         // poco response wrapped in objectcontent         var content = context.response.content objectcontent          if(content != null)         {             // create wrappedjsonresponse object appropriately ,             // put original result in data property             content.value = new wrappedjsonresponse { data = content.value };             content.objecttype = typeof(wrappedjsonresponse);         }     } } 

with attribute, can choose apply want (whole controller, action or default filter).

note: not have access development environment @ moment , have not tested filter. if not complete, should @ least give idea on how can done.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -