筛选出ASP.NET Core API中的属性 [英] Filtering Out Properties in an ASP.NET Core API
问题描述
我想在我的API中提供以下JSON:
I want to serve up the following JSON in my API:
{
"id": 1
"name": "Muhammad Rehan Saeed",
"phone": "123456789",
"address": {
"address": "Main Street",
"postCode": "AB1 2CD"
}
}
我想赋予客户端过滤掉他们不感兴趣的属性的能力.以便以下URL返回JSON的子集:
I want to give the client the ability to filter out properties they are not interested in. So that the following URL returns a subset of the JSON:
`/api/contact/1?include =名称,地址.邮政编码
`/api/contact/1?include=name,address.postcode
{
"name": "Muhammad Rehan Saeed",
"address": {
"postCode": "AB1 2CD"
}
}
在ASP.NET Core中实现此功能的最佳方法是什么?
What is the best way to implement this feature in ASP.NET Core so that:
- 该解决方案可以全局应用,也可以应用于单个控制器或类似过滤器的操作.
- 如果该解决方案使用反射,那么还必须有一种方法,可以通过为其提供一些代码以出于性能原因手动滤除属性来优化特定的控制器动作.
- 它应该支持JSON,但是很好地支持XML等其他序列化格式.
我发现了此解决方案,该解决方案使用了自定义JSON.Net 此代码示例,但不适用于控制器.另外,这是JSON特定的实现.
I found this solution which uses a custom JSON.Net ContractResolver. A contract resolver could be applied globally by adding it to the default contract resolver used by ASP.Net Core or manually to a single action like this code sample but not to a controller. Also, this is a JSON specific implementation.
推荐答案
您可以将dynamic
与ExpandoObject
结合使用,以创建包含所需属性的动态对象. ExpandoObject 是什么dynamic
关键字在后台使用,它允许在运行时动态添加和删除属性/方法.
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);
}
这导致
{"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.
这篇关于筛选出ASP.NET Core API中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!