如何限制OData导致Web API

时间:2015-04-02 09:25:12

标签: c# asp.net-mvc-4 asp.net-web-api

我目前正在开发一个使用WebAPI返回存储在数据库中的数据的应用程序。

现在,我需要能够过滤结果,所以OData到请求,这样我就可以在Queystring中构建一个完整的过滤器。

这是OData的配置:

private static void ConfigureOData(HttpConfiguration config)
{
    ODataModelBuilder builder = new ODataConventionModelBuilder();
    builder.EntitySet<GenericArticle>("GenericArticle");
    config.MapODataServiceRoute(routeName: "ODataRoute", routePrefix: "OData", model: builder.GetEdmModel());

    // Defines the configuration for OData.
    var queryAttribute = new QueryableAttribute
    {
        MaxTop = Convert.ToInt32(ConfigurationManager.AppSettings["OData:MaxTop"]),
        PageSize = 2
    };

    config.EnableQuerySupport(queryAttribute);
}

正在WebApiConfig.cs文件中调用此方法。

Global.asax文件包含以下代码:

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);
    GlobalConfiguration.Configuration.EnsureInitialized();

    UpdateDatabaseToLatestVersion();
}

我用来查询数据的控制器如下:

 [EnableQuery]
 public IQueryable<GenericArticle> Get()
 {
     var data = UnitOfWork.GenericArticlesRepository.Entities;

     return data;
 }

因此,该方法标有EnableQuery属性,控制器也从ODataController继承。

现在,我可以查询一些包含数百万条记录的表格,当然,我甚至不想让GetAll找到它的数据库。

因此,我在WebApiConfig文件中进行了考虑,以下代码就足够了:

var queryAttribute = new QueryableAttribute
{
    MaxTop = Convert.ToInt32(ConfigurationManager.AppSettings["OData:MaxTop"]),
    PageSize = 2
};

但是,这不会限制结果,但是当我使用超过此处定义的MaxTop值的过滤器请求url时会抛出错误。

有没有办法确保即使我请求没有任何过滤参数的网址,结果也只会包含第一个&#39; x&#39;启用了分页的记录?

亲切的问候,

1 个答案:

答案 0 :(得分:0)

如果您想限制提取的记录数,请尝试使用服务器分页选项来过滤记录。

点击此链接 - http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-query-options#server-paging

快乐编码:)