You can do it in a generic way.
Add the following class:
public class SecureJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, HttpContent content, TransportContext transportContext)
{
if ((typeof (IEnumerable).IsAssignableFrom(type)))
{
value = new {result = value};
}
return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
}
}
And now, in your WebApiConfig replace the default JSonMediaTypeFormatter with this new one:
config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, new SecureJsonMediaTypeFormatter());
Now you can return any IEnumerable you wish, like you originally did, i.e.
[HttpGet]
public IEnumerable<MyValue> Values()
{
return db.MyValues.ToList();
}
And the SecureJsonMEdiaTypeFormatter will intercept it, and wrap in an anonymous object, under result property:
{
"result": [
{
"name": "Toronto Maple Leafs",
"league": "NHL"
},
{
"name": "Montreal Canadiens",
"league": "NHL"
}
]
}