设置 WebAPI 2 OData 服务的默认页面大小

Dav*_*mid 5 asp.net odata asp.net-web-api

我有一个 ODataController ,其端点如下:

[EnableQuery]
public IQueryable<Customer> Get()
{
    return _context.Customers;
}
Run Code Online (Sandbox Code Playgroud)

WebApiConfig 的 Register 方法中的此设置:

config.Count().Filter().OrderBy().Expand().Select().MaxTop(100);
Run Code Online (Sandbox Code Playgroud)

有很多客户条目,我不希望客户一次请求太多,因为查询将花费很长时间。幸运的是,这个设置意味着如果他们发出这样的请求:

http://domain.com/api/Customers ?$top=1000

因为它高于 100,所以会阻止他们检索它们。

但是,如果他们提出这样的请求:

http://domain.com/api/Customers

然后,这将尝试检索所有客户,这是我不想要的。

我知道我可以这样设置页面大小:

[EnableQuery(PageSize = 10)]
public IQueryable<Customer> Get()
{
    return _context.Customers;
}
Run Code Online (Sandbox Code Playgroud)

这只会返回 10 个结果,但是我仍然希望用户能够指定自己的 $top 和 $skip 值进行分页(并决定每页需要多少个结果)。我想要的是最多 100 个,默认为 10 个。

我怎样才能实现这个目标?

编辑

我尝试了以下方法,但在使用 Expand 子句时它无法正常工作。还有其他想法吗?

[EnableQuery(MaxTop = 100)]
public IQueryable<Customer> Get(ODataQueryOptions<Customer> queryOptions)
{
    IQueryable<Customer> query = _context.Customers;
    int? top = queryOptions?.Top?.Value;
    if (top == null)
    {
        query = query.Take(10);
    }

    return query;
}
Run Code Online (Sandbox Code Playgroud)

Phi*_* T. 0

我面临着同样的事情,但我能够让它发挥作用。看起来参数的顺序很重要。你必须原谅我,我对此很陌生,并且不断学习,所以我希望这确实有帮助。

我的 API 控制器如下所示:

    [EnableQuery(PageSize=100)]
    public IQueryable<APPLICATION_LOGS> Get()
    {
        return db.APPLICATION_LOGS;
    }
Run Code Online (Sandbox Code Playgroud)

在我的客户端中,我正在构建一个请求并捕获响应:

        string entity = "/AuditApplicationLog";
        string expandOptions = "&$expand=APPLICATION, APPLICATIONS_SUBSYSTEMS, FILE";
        string parameters = "?$top=100&$count=true";
        string url = serviceUri + entity + parameters + expandOptions;
        WebRequest request = WebRequest.Create(url);
        WebResponse response = request.GetResponse();
Run Code Online (Sandbox Code Playgroud)

This is all a practice project that I am just using to teach myself a few concepts.The page size in my API controller is set to 100 but you'll notice in the parameters variable I am setting a top value. If I set this value to 25, it will return 25. If I set it to 50, it will return 50 etc. Apparently the order I set the parameters matters. If I set the top value before the expand parameters, it works. If I attempt to set it after the expand parameters it returns the default 100, regardless of the value I set top at. It does appear to leave out the "nextPage" link, but that can be accounted for. I hope this helps.