[英]OData queries and types other than IQueryable in ASP.NET Web API
我正在构建一个返回Atom或RSS提要的ASP.NET Web API应用程序。 为此,它构建一个System.ServiceModel.Syndication.SyndicationFeed
并且自定义MediaTypeFormatter
负责处理HTTP Accept Header,将SyndicationFeed
转换为Atom10FeedFormatter
或Rss20FeedFormatter
,并将结果传输到响应流。 到现在为止还挺好。
我的控制器看起来像这样:
public class FeedController : ApiController { public HttpResponseMessage Get() { FeedRepository feedRepository = new FeedRepository(); HttpResponseMessage<SyndicationFeed> successResponseMessage = new HttpResponseMessage<SyndicationFeed>(feedRepository.GetSyndicationFeed()); return successResponseMessage; } }
我想要做的是使用内置的OData查询来过滤我的Feed,但是将Get()
方法的返回类型更改为IQueryable<SyndicationFeed>
显然不起作用,因为SyndicationFeed
没有实现IQueryable
。
有没有办法使用内置的OData的查询方式IEnumerable<SyndicationItem>
的财产SyndicationFeed
?
此问题已不再适用,因为Microsoft删除了对Web API的Beta版本中的OData查询的基本支持。
未来版本将包括更完整的OData支持。 可通过CodePlex和NuGet进行早期构建,此处有更多详细信息: http : //blogs.msdn.com/b/alexj/archive/2012/08/15/odata-support-in-asp-net织网,api.aspx
System.Linq命名空间为IEnumerable
接口提供名为AsQueryable的扩展方法。 你的代码看起来像这样:
public class FeedController : ApiController
{
public IQueryable<SyndicationFeed> Get()
{
FeedRepository feedRepository = new FeedRepository();
//TODO: Make sure your property handles empty/null results:
return feedRepository.GetSyndicationFeed()
.YourEnumerableProperty.AsQueryable();
}
}
使用OData时,您不必从控制器返回IQuerable。 检查“直接调用查询选项”部分, 网址为https://docs.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-query-options
对于您的情况,它看起来像:
public SyndicationFeed Get(ODataQueryOptions<SyndicationItem> opts)
{
var settings = new ODataValidationSettings();
opts.Validate(settings);
SyndicationFeed result = feedRepository.GetSyndicationFeed();
result.Items = opts.ApplyTo(result.Items.AsQuerable()).ToArray();
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.