Download Complete Project: WebApiFieldLevelSelection
When you are writing a RESTful web API you often want to allow clients to feed a list of fields to the API that the clients need. The reason is to return only the useful data to the client. Say for example, you have an entity called Product that has many properties. The client may need only a few properties of the Product object. If you return the entire object every time the client asks for a product.
it unnecessarily wastes bandwidth and increases the response time. So to avoid that you can accept a list of fields the client wants and return only those. How can you do that?
Odata is best way to achieve this where you can use $Select command to fetch specific database fields in response.
Problem comes when webapi not implementing odata then how can achieve this functionality ?
To achieve this you have to use some basic .net objects like dynamic,expendoObject or generic collections etc.
Let’s resolve the problem step by step:
- Create empty Webapi Project with controller name as “ProductCategory” with Two Get method.one is parameter less and other with string parameter that will accept comma separated field list in request.
- Get() method will return all fields of database in response while Get(string fields) method accept list of fields and return desired fields in response.
- In below example i have use hardcoded list with dummy values.You may replace it with actual database.
DynamicObject accept the list of fields and return object.here I have use .net reflection to get the value of each fields and respective value to dictionary<string,object> object. later this dictionary object pass to linq query.
- When user pass two fields (productid and productName) as query string in request.you can see only two fields are coming in json response.
- When User pass three fields (productId,ProductName,Price) as query string in request.You can see now three fields are coming with json response.
So you can see how you can implement field level selection on webapi without Odata implementation.