skip to content

In ASP.NET Core OData, what does [EnableQuery] do with an IQueryable<SalesOrder> result, and why can $filter still fail until ODataOptions enables it?

level: middleimportance: must knowfreq 32%

answer

  1. an action filter, not middleware
  2. validates in OnActionExecuting, applies in OnActionExecuted
  3. composes onto the IQueryable you return
  4. QueryConfigurations: every Enable* starts false
  5. AllowedQueryOptions defaults to Supported

basics

~20 s

[EnableQuery] is an MVC action filter that validates the request's OData options, then composes them onto the IQueryable the action returns. Each option must also be enabled on ODataOptions, where Filter, Select and the others start off.

solid answer

~40 s

`EnableQueryAttribute` derives from `ActionFilterAttribute`. In `OnActionExecuting` it parses the query string into `ODataQueryOptions` and validates it against its `ODataValidationSettings`; a failure becomes a **400** `BadRequestObjectResult` before your action runs. In `OnActionExecuted` it takes the returned value and, through `ApplyQuery`, adds `Where`, `OrderBy`, `Skip`, `Take` and a projection for `$select` to the `IQueryable`, which runs only when the serializer enumerates it. There are **two gates**. The global one is `ODataOptions.QueryConfigurations`: `EnableFilter`, `EnableSelect`, `EnableExpand`, `EnableOrderBy`, `EnableCount` and `EnableSkipToken` all default to `false`, and the global `MaxTop` to `0`, until you call `Filter()`, `Select()` and so on, or `EnableQueryFeatures(maxTop)`. The per-action one is the attribute's own settings: `AllowedQueryOptions` defaults to `Supported`, and limits such as `MaxTop` and `PageSize` start unset.

code

csharp · 11 lines
csharp
builder.Services.AddControllers().AddOData(options => options
    .AddRouteComponents("odata", GetEdmModel())
    .Filter().OrderBy().Select().Count()   // gate one: global switches
    .SetMaxTop(500));

public class SalesOrdersController(SalesDb db) : ODataController
{
    // gate two: per-action validation and query settings
    [EnableQuery(MaxTop = 200, PageSize = 100)]
    public IQueryable<SalesOrder> Get() => db.SalesOrders.AsNoTracking();
}

go deeper

for a junior

Remember that [EnableQuery] is an action filter that applies the URL's query options to what your action returns, and that AddOData must also switch each option on.

for a middle

Explain the two moments, validation in OnActionExecuting and composition in OnActionExecuted, and the two gates: QueryConfigurations defaults versus the attribute's AllowedQueryOptions and limits.

for a senior

Show you know which defaults are open (AllowedQueryOptions Supported, no PageSize, EnableQueryFeatures with null MaxTop) and set explicit ceilings on every exposed action.

for a principal

Weigh a global AddODataQueryFilter against per-action attributes: one place is easier to audit, but per-action limits let each surface carry the cost profile it can afford.

## What the attribute is `[EnableQuery]` (`Microsoft.AspNetCore.OData.Query.EnableQueryAttribute`) is an ordinary MVC **action filter**: it derives from `ActionFilterAttribute`, can sit on an action or a controller, and runs in the filter pipeline around the action. It is not middleware and it does not touch requests that reach other endpoints. It works on `ODataController` actions behind an OData route and, with fewer features, on plain `ControllerBase` actions that return a collection. ## Two moments in the request 1. **Before the action — `OnActionExecuting`.** The filter works out the element type (from the OData path, or from the action's return type such as `IQueryable<SalesOrder>`, `Task<...>` or `ActionResult<...>`), builds `ODataQueryOptions` from the query string and calls `ValidateQuery`. On a non-OData controller whose return type hides the element type, such as `IActionResult`, it cannot do this yet and validates after the action instead. Any `ODataException` — an option that is not allowed, a `$top` over the limit, an `$expand` too deep — turns into a `BadRequestObjectResult` (**400**) with a message such as "The query specified in the URI is not valid. The property 'Region' cannot be used in the $filter query option." The action never runs, so no database work is wasted. 2. **After the action — `OnActionExecuted`.** The filter reads the `ObjectResult` value. For an `IQueryable` it calls `ApplyQuery`, which composes the options onto the expression tree — among them `Where` for `$filter`, `OrderBy` for `$orderby`, `Skip` and `Take` for `$skip` and `$top`, and a projection for `$select`/`$expand`. Nothing executes yet. The new `IQueryable` replaces the result value, and the output formatter enumerates it — that is when EF Core sends one SQL statement. For a `SingleResult<T>` the filter applies `$select`/`$expand` to the one-row query; for a non-queryable `IEnumerable` it calls `AsQueryable()` and applies everything in memory. ## Gate one: the global switches on ODataOptions `AddOData(options => ...)` exposes `ODataOptions.QueryConfigurations`, a `DefaultQueryConfigurations`. Its starting values are restrictive: | Setting | Default | Turned on by | |---|---|---| | `EnableFilter` | `false` | `Filter()` | | `EnableSelect` | `false` | `Select()` | | `EnableExpand` | `false` | `Expand()` | | `EnableOrderBy` | `false` | `OrderBy()` | | `EnableCount` | `false` | `Count()` | | `EnableSkipToken` | `false` | `SkipToken()` | | `MaxTop` | `0` | `SetMaxTop(n)`; `null` removes the ceiling | `EnableQueryFeatures(maxTopValue)` flips all six switches and sets `MaxTop` in one call; its `maxTopValue` parameter defaults to `null`, which means **no** upper limit. These settings feed the model-bound checks, so `$filter=Region eq 'EU'` fails with "cannot be used in the $filter query option" until `Filter()` is called — or the model itself marks the type filterable, for example with the model builder's `[Filter]` attribute — even though the action has `[EnableQuery]`. ## Gate two: the attribute's own settings The attribute carries an `ODataValidationSettings` and an `ODataQuerySettings`: - `AllowedQueryOptions` defaults to `AllowedQueryOptions.Supported` — `$filter`, `$orderby`, `$top`, `$skip`, `$skiptoken`, `$count`, `$select`, `$expand`, `$format`, `$apply`, `$compute` and `$search`, but not `$deltatoken`. - `MaxTop`, `MaxSkip` and `PageSize` start unset, so the attribute imposes no row ceiling of its own. - `MaxExpansionDepth` is 2, `MaxNodeCount` 100, `MaxAnyAllExpressionDepth` 1 and `MaxOrderByNodeCount` 5. - `EnsureStableOrdering` is `true`: when `$top`, `$skip` or paging is in play and the client gave no `$orderby`, the filter orders by the key so pages are deterministic. A request must pass **both** gates. Narrowing one never widens the other: `[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.Top, MaxTop = 10)]` still fails `$top=100` if the global ceiling is `SetMaxTop(2)`, and an attribute that allows `$filter` cannot override a global `EnableFilter` of `false`. ## Practical consequences - **Return the `IQueryable`, not a list**, so the composition reaches the database instead of filtering rows already in memory. - **Do not add `[EnableQuery]` when the action already applies `ODataQueryOptions<T>` itself** — the filter would apply the options a second time over the already-shaped result. - `services.AddODataQueryFilter()` registers a filter provider that attaches an `EnableQueryAttribute` to every action returning `IQueryable` or `SingleResult`; prefer the attribute per action so each surface states its own limits. - Because validation happens before the action, a client mistake costs no query; because composition happens after, the action stays a one-liner such as `db.SalesOrders.AsNoTracking()`. - The filter only composes when there is something to apply: a non-empty query string, a `PageSize`, a `SingleResult` or a `$count` request. A bare `GET /odata/SalesOrders` with no options and no page size of any kind returns the queryable as it is — every row. - A non-success result, such as `NotFound()` or a 400 your action returns, is passed through untouched; the filter applies options only to successful object results.

  • Why does a request with an invalid $filter never hit the database even though the IQueryable is built in the action?
    `EnableQueryAttribute.OnActionExecuting` parses and validates the options before the action executes and sets a 400 result on failure, so the action is skipped. Even in the success case the action only builds an expression; the query runs when the formatter enumerates the composed `IQueryable` after `OnActionExecuted`.
  • What does EnableQueryFeatures() without an argument do to $top?
    It enables expand, select, filter, orderby, count and skiptoken globally and calls `SetMaxTop(null)`, because `maxTopValue` defaults to `null`. Null means no global upper limit, so unless the action's `[EnableQuery]` sets `MaxTop` or `PageSize`, a client can ask for any number of rows.
  • Does [EnableQuery] work on an ordinary ControllerBase action that returns IEnumerable<T>?
    Yes: the filter handles non-OData JSON controllers by reading the element type from the declared return type, validating before the action and applying the options afterwards. If the returned value is not an `IQueryable`, it wraps it with `AsQueryable()` and the query runs in memory over whatever the action already loaded.

  • [EnableQuery] is middleware that rewrites the SQL before the action runs
  • Putting [EnableQuery] on an action is enough to allow $filter and $select
  • Setting AllowedQueryOptions on the attribute overrides the global Filter() switch
  • EnableQueryFeatures() with no argument keeps a safe default $top ceiling
  • An invalid $filter is only detected after the database query has run