What approach should I use if I want to return only some of fields from the model? I want to be able to ask for some fields, something like this:
?fields=email,expiration_date,avatar(thumb_width,thumb_height,thumb_url)
This expression could be also header in the request. I also have nested objects, like the Avatar inside the User.
This will save me hundred of MB of traffic, since some of my models are really heavy ones.
UPDATE: Field selection should work both with Json and XML responses.
Depending on which of these is returned, Web API uses a different mechanism to create the HTTP response. Convert directly to an HTTP response message. Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message. Write the serialized return value into the response body; return 200 (OK).
You can return one or the other, not both. Frankly, a WebAPI controller returns nothing but data, never a view page. A MVC controller returns view pages. Yes, your MVC code can be a consumer of a WebAPI, but not the other way around.
I found a nuget package that does this for you
WebApi.PartialResponse
Git hub source code:
https://github.com/dotarj/PartialResponse
It essentially wraps the formatter discussed above, so that you only have to configure it like this:
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new PartialJsonMediaTypeFormatter() { IgnoreCase = true });
Then, you can specify ?fields=<whatever>
in your request, and it will return the model with only those fields specified.
I would replace the default contract resolver (see http://frankapi.wordpress.com/2012/09/09/going-camelcase-in-asp-net-mvc-web-api/) with a custom one, override the GetSerializableMembers method from the Newtonsoft.Json.Serialization.DefaultContractResolver class and filter its results with the value of the querystring fields.
Whether you can access the querystring from that class is another question, you may be able to use the static httpcontext.current to get it, but there may be a cleaner option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With