我有一个使用 ASP .NET MVC 4 提供的 WebAPI 制作的 Web 服务。
我知道 WebAPI 之上的层会自动处理 OData 查询(例如 $filter
、$top
、$skip
),但是如果我想自己处理过滤怎么办?
I don't simply return data from my database ,但我还有另一个层,它添加了一些属性,进行了一些转换等。因此,查询所有数据、转换它们并将它们返回到 WebAPI 类以进行 OData 过滤还不够好。这当然非常慢,而且通常是一个蹩脚的主意。
有没有办法将 OData 查询参数从我的 WebAPI 入口点传播到我调用以获取和转换数据的函数?
例如,对 /api/people?$skip=10&$top=10
的 GET 将在服务器上调用:
public IQueryable<Person> get() {
return PersonService.get(SomethingAboutCurrentRequest.CurrentOData);
}
在PersonService
中:
public IQueryable<Person> getPeople(var ODataQueries) {
IQueryable<ServerSidePerson> serverPeople = from p in dbContext.ServerSidePerson select p;
// Make the OData queries
// Skip
serverPeople = serverPeople.Skip(ODataQueries.Skip);
// Take
serverPeople = serverPeople.Take(ODataQueries.Take);
// And so on
// ...
// Then, convert them
IQueryable<Person> people = Converter.convertPersonList(serverPeople);
return people;
}
最佳答案
我刚刚偶然发现了这篇旧文章,我添加了这个答案,因为现在自己处理 OData 查询非常容易。这是一个例子:
[HttpGet]
[ActionName("Example")]
public IEnumerable<Poco> GetExample(ODataQueryOptions<Poco> queryOptions)
{
var data = new Poco[] {
new Poco() { id = 1, name = "one", type = "a" },
new Poco() { id = 2, name = "two", type = "b" },
new Poco() { id = 3, name = "three", type = "c" }
};
var t = new ODataValidationSettings() { MaxTop = 2 };
queryOptions.Validate(t);
//this is the method to filter using the OData framework
//var s = new ODataQuerySettings() { PageSize = 1 };
//var results = queryOptions.ApplyTo(data.AsQueryable(), s) as IEnumerable<Poco>;
//or DIY
var results = data;
if (queryOptions.Skip != null)
results = results.Skip(queryOptions.Skip.Value);
if (queryOptions.Top != null)
results = results.Take(queryOptions.Top.Value);
return results;
}
public class Poco
{
public int id { get; set; }
public string name { get; set; }
public string type { get; set; }
}
关于rest - ASP.NET MVC 4 WebApi : Manually handle OData queries,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10781309/