asp.net-mvc - 从 ASP.NET Web API 返回一些字段

标签 asp.net-mvc asp.net-mvc-4 asp.net-web-api json.net

如果我只想从模型中返回一些字段,我应该使用什么方法?我希望能够询问一些字段,如下所示:

?fields=email,expiration_date,avatar(thumb_width,thumb_height,thumb_url)



此表达式也可以是请求中的 header 。我也有嵌套的对象,比如 User 中的 Avatar。

这将为我节省数百 MB 的流量,因为我的一些模型真的很重。

更新:字段选择应该适用于 Json 和 XML 响应。

最佳答案

我找到了一个为你做这个的 nuget 包

WebApi.PartialResponse

Git 中心源代码:
https://github.com/dotarj/PartialResponse

它基本上包装了上面讨论的格式化程序,因此您只需像这样配置它:

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new PartialJsonMediaTypeFormatter() { IgnoreCase = true });

然后,您可以指定 ?fields=<whatever>在您的请求中,它将返回仅指定那些字段的模型。

关于asp.net-mvc - 从 ASP.NET Web API 返回一些字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12662259/

相关文章:

javascript - 如果使用 GET 方法,AJAX 请求无法将 DateTime 传递到服务器

c# - asp.net中MySQL的连接字符串是什么

c# - 多个可选参数路由

c# - ASP.NET Web API - 请求特定的全局变量

c# - ASP.Net MVC : How to read my custom claims value

c# - 以mvc形式上传

azure - 错误 : The resource you are looking for has been removed, 已更名,或暂时不可用

c# - 使用 Entity Framework Core 更新相关数据

javascript - 如何为这种情况构建 Knockout JS(使用 ASP.NET MVC)

c# - 使用javascript为模型赋值