Wrapping a Web API response in JSON but still having it work with IQueryable and oData

╄→尐↘猪︶ㄣ 提交于 2021-02-07 04:19:47

问题


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 } ]
}

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.

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?


回答1:


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);
}

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



来源:https://stackoverflow.com/questions/14720641/wrapping-a-web-api-response-in-json-but-still-having-it-work-with-iqueryable-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!