In ASP. NET Web API, partial fields in the object are displayed through Uris.
Sometimes we may not want to display all fields in an object. For example, the client sends the following request:
Locaohost: 43321/api/groups/1/items? Fields = id
Locaohost: 43321/api/groups/1/items? Fields = id, name
Above, for the Item class, we may only want to display the id, or want to display the id and name, and so on.
How to implement it?
→ The backend accepts the value of the query string fields and splits the string to an array or set.
→ Traverse these fields, obtain the value of the field using reflection, and store each key value
Suppose there are the following fields:
public class Group{ public int Id{get;set;} public int UserId{get;set;} public string Title{get;set;} public string Descritpion{get;set;} public int StatusId{get;set;} public ICollection<Item> Items{get;set;}}public class Item{ public int Id{get;set;} public string Name{get;set;}}
The Controller for Item is as follows:
Public class ItemsController: ApiController {[Route ("groups/{groupId}/items", Name = "ItemsForGroup")] public IHttpActionResult Get (int groupId, string fields = null) {List <string> lstOfFields = new List <string> (); if (fields! = Null) {lstOfFields = fields. toLower (). split (''). toList ();} var result = _ repo. getItems (). toList (). select (e => ItemFactory. createDataShapedObject (e, lstOfFields); return OK (result) ;}} public staic class ItemFactory {public object CreateDataShapedObject (Item item, List <string> lstOfFields) {if (! LstOfFields. any () {return item;} else {// runtime object ExpandObject objectToReturn = new ExpandObject (); foreach (var field in lstOfFields) {// obtain the field value var fieldValue = item. getType (). getProperty (field, BindingFlags. ignoreCase | BindingFlags. public | BindingFlags. instance ). getValue (item, null); (IDictionary <string, object>) objectToReturn ). add (field, fieldValue);} return objectToReturn ;}}}
In the preceding example, ExpandObject is a runtime object that implements the IDictionary <string, object> interface. through reflection, the field is used as the key of ExpandObject and the field value is used as the value of ExpandObject.