skip to content

You expose SalesOrders through ASP.NET Core OData to an analytics tool; which [EnableQuery] and ODataOptions settings stop it from pulling the whole table or running runaway queries?

level: seniorimportance: should knowfreq 22%

answer

  1. server-driven paging, not trust in $top
  2. PageSize emits @odata.nextLink
  3. SetMaxTop plus the attribute's MaxTop
  4. MaxExpansionDepth = 0 disables the check
  5. AllowedFunctions, AllowedOrderByProperties, MaxNodeCount 100

basics

~20 s

Set PageSize so every response is a page with a next link, cap $top globally with SetMaxTop and per action with MaxTop, and narrow AllowedQueryOptions, AllowedFunctions, AllowedOrderByProperties, MaxExpansionDepth and MaxNodeCount to what the tool needs.

solid answer

~40 s

I would make **server-driven paging** the guarantee: `[EnableQuery(PageSize = 500)]` makes every response at most 500 rows with an `@odata.nextLink`, whatever the client sends. Then cap explicit requests twice: `SetMaxTop(1000)` in `AddOData` (never `EnableQueryFeatures()` with its `null` default) and `MaxTop = 1000` on the attribute, plus `MaxSkip` if deep offsets hurt. Next, shrink the query language: `AllowedQueryOptions` without `Apply`, `Compute` and `Search` if the tool does not need them, `AllowedFunctions` without the string functions that defeat indexes, `AllowedOrderByProperties = "OrderedAt,Total"` to match the indexes, `MaxNodeCount` lower than its 100 default, and either no `Expand()` at all or a small `MaxExpansionDepth` — remembering that **0 disables** the depth check rather than forbidding `$expand`. Finally, keep sensitive or unindexed columns out of the EDM so they cannot be selected or filtered.

code

csharp · 12 lines
csharp
public class SalesOrdersController(SalesDb db) : ODataController
{
    [EnableQuery(
        PageSize = 500,
        MaxTop = 1000,
        MaxSkip = 50_000,
        MaxNodeCount = 40,
        MaxExpansionDepth = 1,
        AllowedFunctions = AllowedFunctions.AllDateTimeFunctions,
        AllowedOrderByProperties = "OrderedAt,Total")]
    public IQueryable<SalesOrderFact> Get() => db.SalesOrderFacts.AsNoTracking();
}

go deeper

for a junior

Know that an OData endpoint must page its results with PageSize and cap $top, otherwise one request can read an entire table.

for a middle

Explain the two layers, ODataOptions and [EnableQuery], and the defaults of PageSize, MaxTop, MaxNodeCount and MaxExpansionDepth that matter for cost.

for a senior

Design the full fence for a client you cannot review: paging, both MaxTop layers, narrowed options, functions and sort properties, a trimmed EDM, and the 0-disables trap.

for a principal

Decide whether a generic query surface is the right contract for analytics at all, compared with a fixed reporting endpoint or an export, and who owns its cost.

## The scenario An analytics tool will read a `SalesOrders` entity set over OData. It generates queries itself, so you cannot review each one: the protection has to be in the server's configuration. In ASP.NET Core OData that configuration lives in two places — the global `ODataOptions` passed to `AddOData`, and the `[EnableQuery]` attribute (`EnableQueryAttribute`) on the action — and **a request must pass both**. ## Bound the rows: paging first, $top second A cap on `$top` only constrains clients that send `$top`. A client that sends nothing gets everything unless the server pages. So the first setting is **`PageSize`**: - `[EnableQuery(PageSize = 500)]` makes the filter apply its own `Take` and append an `@odata.nextLink` to the response when more rows exist. The client follows next links; each page is one bounded query. - `PageSize` is unset by default, so without it there is no server-side row limit at all. - `EnsureStableOrdering` defaults to `true`: when paging, `$top` or `$skip` applies and the client gave no `$orderby`, the filter orders by the key so pages do not overlap. Make sure the key is the clustered or an indexed column. - If the tool uses `$skiptoken` continuation, enable it globally with `SkipToken()`; otherwise next links are built from `$skip`, and `MaxSkip` on the attribute caps how deep an offset may go. Then cap explicit `$top` at both layers: | Layer | Setting | Default | Note | |---|---|---|---| | Global | `SetMaxTop(n)` on `ODataOptions` | `0` | `SetMaxTop(null)` and `EnableQueryFeatures()` with no argument remove the ceiling | | Action | `[EnableQuery(MaxTop = n)]` | unset | validated before the action; over-limit requests get 400 | | Action | `[EnableQuery(MaxSkip = n)]` | unset | bounds deep offset paging | ## Bound the shape of each query Row counts are not the only cost. A `$filter` can be a long expression, an `$expand` can join several tables, an `$orderby` can sort on an unindexed column. The attribute's validation settings exist for this: 1. **`AllowedQueryOptions`** defaults to `Supported` (everything except `$deltatoken`). An analytics read model rarely needs `$apply`, `$compute` or `$search`; list only what the tool uses, for example `Filter | OrderBy | Top | Skip | Select | Count`. 2. **`AllowedFunctions`** defaults to `AllFunctions`. Removing string functions such as `contains` stops `contains(CustomerName,'a')` from becoming a substring search that no ordinary index can serve. 3. **`AllowedOrderByProperties`** is a comma-separated list on the attribute, such as `"OrderedAt,Total"`; any other sort property fails validation. 4. **`MaxNodeCount`** (default 100) caps the size of the parsed `$filter` tree; **`MaxAnyAllExpressionDepth`** (default 1) caps nested `any`/`all`; **`MaxOrderByNodeCount`** (default 5) caps sort keys. 5. **`$expand`**: if the tool does not need order lines, never call `Expand()` globally and the option fails validation. If it does, keep **`MaxExpansionDepth`** at its default of 2 or lower it to 1. Setting it to **0 disables the depth check** — a common misreading that removes the guard instead of tightening it. To forbid expansion, leave `Expand` out of `AllowedQueryOptions`. 6. **`$count=true`** asks for a separate count over the filtered set. If the table is huge and the tool does not need totals, leave `Count()` off. ## Bound what can be named at all The EDM is the outer fence: a property the model does not contain cannot be selected, filtered or sorted. Register a read-model type with only the columns the tool should see — no customer e-mail, no internal margin — rather than the full EF Core entity. Then return `db.SalesOrderFacts.AsNoTracking()` as an `IQueryable` so every composed option is translated by the provider instead of evaluated over rows already loaded. ## A configuration that holds ```csharp builder.Services.AddControllers().AddOData(o => o .AddRouteComponents("odata", model) .Filter().OrderBy().Select().SkipToken() .SetMaxTop(1000)); [EnableQuery(PageSize = 500, MaxTop = 1000, MaxNodeCount = 40, AllowedQueryOptions = AllowedQueryOptions.Filter | AllowedQueryOptions.OrderBy | AllowedQueryOptions.Top | AllowedQueryOptions.Select | AllowedQueryOptions.SkipToken, AllowedOrderByProperties = "OrderedAt,Total")] public IQueryable<SalesOrderFact> Get() => db.SalesOrderFacts.AsNoTracking(); ``` ## What the library does not do - It does not time out a slow query: that is the database command timeout and the request's cancellation. - It does not limit how often the tool calls you: rate limiting is separate middleware. - It does not know your indexes: `AllowedOrderByProperties` and the EDM are how you align the query language with them.

  • A colleague sets MaxExpansionDepth = 0 to forbid $expand. What actually happens?
    The depth check is skipped: the validator only enforces `MaxExpansionDepth` when it is greater than 0, and the property's own documentation says 0 disables it. Expansion is then limited only by whether `Expand()` was enabled globally. To forbid it, leave `Expand` out of `AllowedQueryOptions` or never call `Expand()` on `ODataOptions`.
  • Why is PageSize a better guarantee than MaxTop for an analytics client?
    `MaxTop` only rejects requests that send a large `$top`; a request with no `$top` is not limited by it. `PageSize` applies to every response: the filter takes at most that many rows and adds an `@odata.nextLink`, so a client that asks for everything receives it one bounded page at a time.

  • Setting MaxExpansionDepth to 0 forbids $expand
  • A MaxTop cap alone stops a client from reading the whole table
  • EnableQueryFeatures() with no argument applies a sensible default $top limit
  • AllowedQueryOptions starts empty, so nothing is exposed until listed
  • Exposing the full EF Core entity is fine because $select hides unused columns