In the code below I am manually creating a json object that adheres to our standard json response object format, which is the same for both errors and actual responses:
{
data : { /*something*/ },
status : { httpCode : 123, message: "error message" }
}
How can I configure ASP.NET to do this formatting for me? It can obviously do so using the standard JSON and XML formatter when doing content negotiation, but the linked article only points to a page on Custom Formatters that is blank (and also for ASP.NET MVC which I am not using)...
I would also like for it to be able to set the returned http code in the response object (as shown below).
Current manual formatting of json
[StandardizedRestServiceExceptionFilter]
public class FooController : ApiController
{
/// <summary>
///
/// The return format for both real results and errors
/// is { data : { }, status : { httpCode : 123, message: "error message" }
///
/// We have moved the error serialization to StandardizedRestServiceExceptionFilter,
/// but was unable to generalize the processing of the output format for normal responses
/// That could be improved, possibly using a IMessageFormatter ?
/// </summary>
/// <param name="code"></param>
/// <returns></returns
[HttpGet]
public JObject Coverage(string code)
{
dynamic returnObject = new JObject();
dynamic statusObject = new JObject();
dynamic dataObject = new JObject();
JArray stores = StoresWithCoverage(code);
var hasCoverage = stores.Count > 0;
dataObject.coverage = hasCoverage;
returnObject.data = dataObject;
returnObject.status = statusObject;
statusObject.message = "";
statusObject.httpCode = 200;
return returnObject;
}
}
}
So in the above example I would like to be able to just return an Object of some kind with a coverage
property and have ASP.NET do the actual formatting and serialization to JSON (if requested in the content negotiation).