rest - ASP.NET MVC 4 WebApi : Manually handle OData queries

标签 rest odata asp.net-mvc-4 asp.net-web-api

我有一个使用 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/

相关文章:

angular - 来自服务的同步 Angular 8 HTTP 请求

unix - JerseyTest Grizzly Web 服务器在 Unix 上的行为

rest - 将 SAML 响应从 Web 应用程序传递到 REST API 以进行身份​​验证?

c# - OData 中的实体继承

javascript - 断言失败: The value that #each loops over must be an Array Embers js

c# - 尝试使用工具 Effort : The type date is not a qualified namespace 运行单元测试时 MVC4 应用程序出错

web-services - RESTful 比 SOAP 更快吗?何时使用其中之一?

filter - O数据 : Operands of logical operator 'AND' are not valid

带有 $expand 的 OData 查询,但根为空 $select

mysql - 在 cshtml 中创建新闻源