Return some fields from ASP.NET Web API

What approach should I use if I want to return only some fields from the model? I want to be able to query some fields, something like this:

? = Email fields, expiration_date, avatar (thumb_width, thumb_height, thumb_url)

This expression may also be the header in the request. I also have nested objects such as an Avatar inside a user.

This will save me hundreds of MB of traffic, as some of my models are really heavy.

UPDATE: Field selection should work with both Json and XML responses.

+6
source share
3 answers

I found a nuget package that does this for you

WebApi.PartialResponse

Git source code for the hub:
https://github.com/dotarj/PartialResponse

It essentially wraps the formatter discussed above, so you only need to configure it as follows:

GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.Formatters.Add(new PartialJsonMediaTypeFormatter() { IgnoreCase = true }); 

Then you can specify ?fields=<whatever> in your request and return the model with the specified fields only.

+6
source

I would replace the default recognizer (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 class Newtonsoft.Json.Serialization.DefaultContractResolver and filter its results using the value of the query fields.

If you can access querystring from this class, this is another question, you can use static httpcontext.current to get it, but there might be a cleaner option.

+2
source

You can also use OData. This gives you great flexibility with respect to requests and APIs. http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/create-an-odata-v4-endpoint

In your case, you should use $ select . I also assume that Avatar is another class, so you need to use $ expand for this.

 /api/endpoint?$select=email,expiration_date&$expand=avatar($select=thumb_width,thumb_height,thumb_url) 

I am not 100% if the syntax for the subtitle is right, but I think it is.

0
source

Source: https://habr.com/ru/post/926613/


All Articles