如果我只想从模型中返回一些字段,我应该使用什么方法?我希望能够询问一些字段,如下所示:
?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/