Filtering properties in the ASP.NET API

I want to use the following JSON in my API:

{
  "id": 1
  "name": "Muhammad Rehan Saeed",
  "phone": "123456789",
  "address": {
    "address": "Main Street",
    "postCode": "AB1 2CD"
  }
}

I want to give the client the ability to filter out properties that they are not interested in. Thus, the following URL returns a subset of JSON:

`/api/contact/1?include=name,address.postcode

{
  "name": "Muhammad Rehan Saeed",
  "address": {
    "postCode": "AB1 2CD"
  }
}

What is the best way to implement this feature in the ASP.NET core so that:

  • The solution can be applied globally or on a single controller or as a filter.
  • If the solution uses reflection, then there should also be a way to optimize a specific controller action by providing it with some code to automatically filter out properties for performance reasons.
  • It should support JSON, but it would be nice to support other serialization formats, such as XML.

, JSON.Net ContractResolver. - , , ASP.Net Core, , . , JSON.

+4
1

dynamic ExpandoObject , . ExpandoObject - , dynamic , / .

[HttpGet("test")]
public IActionResult Test()
{
    dynamic person = new System.Dynamic.ExpandoObject();

    var personDictionary = (IDictionary<string, object>)person;
    personDictionary.Add("Name", "Muhammad Rehan Saeed");

    dynamic address = new System.Dynamic.ExpandoObject();
    var addressDictionary = (IDictionary<string, object>)address;
    addressDictionary.Add("PostCode", "AB1 2CD");

    personDictionary.Add("Address", address);

    return Json(person);
}

{"Name":"Muhammad Rehan Saeed","Address":{"PostCode":"AB1 2CD"}}

/ - , .

+2

All Articles