Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return some fields from ASP.NET Web API

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.

like image 732
Viktor Avatar asked Sep 30 '12 15:09

Viktor


People also ask

How do I return content in Web API?

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).

Can we return view from ASP Net Web API method?

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.


2 Answers

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.

like image 51
Alex Avatar answered Sep 30 '22 14:09

Alex


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.

like image 33
Betty Avatar answered Sep 30 '22 15:09

Betty