Filtering Out Properties in an ASP.NET Core API

爷,独闯天下 提交于 2019-12-01 18:07:14

You can use dynamic with ExpandoObject to create a dynamic object containing the properties you need. ExpandoObject is what a dynamic keyword uses under the hood, which allows adding and removing properties/methods dynamically at runtime.

[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);
}

This results in

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

You'd just need to create a service/converter or something similar that will use reflection to loop through your input type and only carry over the properties you specify.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!