【发布时间】:2016-05-20 09:39:11
【问题描述】:
对于我的 ASP.NET MVC Web 服务,我有一个模型,我将其作为 JSON 对象返回。现在我的模型中有一些属性我不想返回。
示例模型:
class Account {
public int ID { get; }
public string Username { get; }
public string Password { get; }
//... more properties
}
假设我只想将 ID 和 Username 属性作为 JSON 返回。我正在寻找一种仅过滤这些属性的好方法。更改访问修饰符不是我的选择。
我能想到的一个解决方案是创建一个如下所示的白名单。在这里,我添加了一个 DisplayName,能够自定义这是一件好事,但这不是必需的。
class FilterProperty
{
public string PropertyName { get; }
public string DisplayName { get; }
public FilterProperty(string propertyName, string displayName)
{
PropertyName = propertyName;
DisplayName = displayName;
}
}
class Account
{
public static FilterProperty[] Whitelist = {
new FilterProperty("ID", "accountId"),
new FilterProperty("Username", "accountName")
};
//...
}
此解决方案的缺点是:如果我要更改属性的名称,我也需要更改白名单。
我可以完成这项工作还是有更好的解决方案?
【问题讨论】:
-
查看这篇文章,无论是在发帖还是发帖:odetocode.com/blogs/scott/archive/2012/03/11/…。特别是检查强类型方法,特别是使用接口来限制模型。
-
你能创建 AccountDto,映射你想要的值,然后返回 AccountDto 而不是 Account?
-
@hellwd 这个我试过了,但是这使我拥有的模型数量增加了一倍,这似乎不是很有效
-
拥有更多模型并不意味着给您的应用程序增加额外的负担。你如何使用它们是唯一的问题。
-
只返回一个只包含你想要的属性的匿名对象。
标签: c# asp.net json asp.net-mvc asp.net-web-api