将Web API响应包装为JSON,但仍可与IQueryable和oData一起使用 [英] Wrapping a Web API response in JSON but still having it work with IQueryable and oData

查看:75
本文介绍了将Web API响应包装为JSON,但仍可与IQueryable和oData一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET Web API项目,并且我想在该项目中使用带有ASP.NET oData预览包的oData筛选器.这意味着我需要使用IQueryable作为响应类型.

I have an ASP.NET Web API project, and I want to use oData filters in the project, with the ASP.NET oData preview package. This means I need to use IQueryable as the response type.

不幸的是,消费者需要这样包装响应:

Unfortunately, the consumer requires the response wrapped like so:

{
   "total": 2,
   "success": true,
   "data": [ 
           { object1 },
           { object2 } ]
}

我创建了一个包装对象,该包装对象将原始版本的IQueryable响应分配给"data"属性,并同时设置了"total"和"success"属性的值.这将创建消费者正在寻找的JSON响应.但这不再是IQueryable,这意味着我无法实现oData过滤器.

I created a wrapper object which assigns the IQueryable response from my original version to the "data" property, and sets the values for the "total" and "success" properties as well. This creates the JSON response the consumer is looking for. But it's no longer IQueryable, which means I can't implement oData filters.

我希望通过设置其枚举数等方式获取包装对象并使其实现IQueryable.但是,我认为这不起作用,因为我必须分配Provider和Expression属性才能实现该接口,并且不知道我应该放在那里.我在IoC中使用存储库模式,并且EntityFramework Code First数据访问位于单独的项目中,使用Ninject将具体对象分配给接口占位符.也许我可以从数据访问层一直提取接口,以便Repository对象携带对IQueryProvider的引用.您认为这可行吗,并允许它支持自动化的oData集成?

I was hoping to take my wrapper object and make it implement IQueryable by setting its enumerators, etc. However, I don't think this will work because I have to assign the Provider and Expression properties to implement the interface, and I don't know what I should put there. I'm using a Repository pattern with IoC, and the EntityFramework Code First data access is in a separate project, with concrete objects assigned to the interface placeholders using Ninject. Perhaps I can abstract out the interfaces all the way from the data access layer so that the the Repository objects carry a reference to an IQueryProvider. Do you think this would work, and allow it to support the automated oData integration?

推荐答案

这是您的操作方法.在后台,[Queryable]仅创建ODataQueryOptions的实例,然后将其应用于您返回的可查询对象.好消息是您可以参数绑定ODataQueryOptions并获得如下所示的代码:

Here's how you do it. Behind the scenes, [Queryable] just creates an instance of ODataQueryOptions and then applies it to the queryable you return. The good news is that you can parameter bind ODataQueryOptions and have code that looks like this:

public Wrapper<MyObject> Get(ODataQueryOptions<MyObject> queryOptions)
{
    IQueryable<MyObject> queryResults = queryOptions.ApplyTo(dbSet);
    return Wrap(queryResults);
}

您甚至不再需要[Queryable],因为您正在做它本来可以为您做的事情.希望有帮助.

You don't even need [Queryable] anymore because you're doing what it would have done for you. Hope that helps.

这篇关于将Web API响应包装为JSON,但仍可与IQueryable和oData一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆