skip to content

In ASP.NET Core output caching, how do AddBasePolicy and AddPolicy differ, and in what order are base and endpoint policies applied?

level: middleimportance: should knowfreq 40%

answer

  1. base: every request through the middleware
  2. named: opt-in by CacheOutput("name")
  3. [OutputCache(PolicyName = ...)]
  4. base first, endpoint last wins
  5. NoCache() opts one endpoint out

basics

~20 s

AddBasePolicy applies a policy to every request the middleware sees; AddPolicy registers a named policy that only endpoints referencing it through CacheOutput("name") or [OutputCache(PolicyName = ...)] use. Base policies run first and endpoint policies after, so the endpoint's settings win.

solid answer

~40 s

Both are methods on `OutputCacheOptions`, called inside `AddOutputCache`. A base policy joins the policy list of every request that passes through `UseOutputCache`, so `options.AddBasePolicy(b => b.Expire(TimeSpan.FromSeconds(30)))` caches every eligible endpoint in the app. A named policy, such as `options.AddPolicy("Listings", b => b.Expire(TimeSpan.FromMinutes(10)))`, does nothing until an endpoint references it; names are case-insensitive and a second registration under the same name replaces the first. Per request the middleware runs the base policies in registration order, then the endpoint's `IOutputCachePolicy` metadata, then its `[OutputCache]` attribute. They all write to one `OutputCacheContext`, so a later `Expire` overrides an earlier one and an endpoint's `NoCache()` switches caching off under a base policy. Builder-made policies include the default policy unless `excludeDefaultPolicy: true`. A misspelled policy name throws nothing; it simply contributes no settings.

code

csharp · 10 lines
csharp
builder.Services.AddOutputCache(options =>
{
    options.AddBasePolicy(b => b.Expire(TimeSpan.FromSeconds(30)));
    options.AddPolicy("Listings", b => b.Expire(TimeSpan.FromMinutes(10)));
});

app.MapGet("/lineup", GetLineup).CacheOutput("Listings");   // 10 minutes
app.MapGet("/news", GetNews);                                 // 30 seconds (base)
app.MapGet("/tickets/basket", GetBasket)
   .CacheOutput(b => b.NoCache());                             // never cached

go deeper

for a junior

Know that base policies cover every request and named policies are opt-in by name through CacheOutput or [OutputCache(PolicyName = ...)].

for a middle

Explain the per-request order (base, endpoint metadata, attribute), that later policies overwrite settings while tags accumulate, and how NoCache opts an endpoint out.

for a senior

Call out the silent failures: a misspelled policy name, excludeDefaultPolicy disabling lookup and storage, and a typed policy instance shared across requests.

for a principal

Argue when a global base policy is acceptable versus requiring each endpoint to opt in, given that a base policy caches endpoints no one has reviewed for per-user content.

## Where policies are declared All output cache policies live on **`OutputCacheOptions`**, configured in `builder.Services.AddOutputCache(options => ...)`. Two methods put them there, and they answer different questions: - **`AddBasePolicy`**: "what applies to *every* request the middleware sees?" - **`AddPolicy(name, ...)`**: "what reusable recipe can endpoints *opt into* by name?" Each has overloads taking an `IOutputCachePolicy` instance or an `Action<OutputCachePolicyBuilder>`, plus a third overload with `bool excludeDefaultPolicy`. ## Base policies ```csharp builder.Services.AddOutputCache(options => { options.AddBasePolicy(b => b.Expire(TimeSpan.FromSeconds(30))); options.AddBasePolicy(b => b .With(c => c.HttpContext.Request.Path.StartsWithSegments("/lineup")) .Tag("lineup")); }); ``` The first line makes **every** eligible endpoint cacheable for 30 seconds, because a builder-made policy starts from the default policy. The second uses `With(predicate)` to apply only to some paths; when the predicate is `false` the wrapped policy contributes nothing to that request. Base policies are the way to say "cache the whole public site" without decorating each endpoint. ## Named policies ```csharp options.AddPolicy("Listings", b => b .Expire(TimeSpan.FromMinutes(10)) .SetVaryByQuery("day", "stage")); app.MapGet("/lineup", GetLineup).CacheOutput("Listings"); ``` Controllers and Razor Pages reference the same policy with `[OutputCache(PolicyName = "Listings")]`. Points worth knowing: - Names are compared **case-insensitively**, and registering a name twice replaces the earlier policy. - The lookup happens per request. An unknown name returns no policy and **no exception**, so a typo means the endpoint is quietly uncached (unless a base policy caches it). - `AddPolicy<T>()` and `AddPolicy(typeof(T))` on the builder create `T` once with `ActivatorUtilities` from the root service provider, so treat a typed policy as a singleton. ## How the middleware combines them For each request the middleware builds one ordered list: 1. all base policies, in the order they were added; 2. the `IOutputCachePolicy` that `CacheOutput(...)` placed in endpoint metadata; 3. the policy built from an `[OutputCache]` attribute. Every policy writes to the same `OutputCacheContext`, so **later writers win**: | Setting | Base says | Endpoint says | Result | |---|---|---|---| | expiration | `Expire(30 s)` | `Expire(10 min)` | 10 minutes | | query vary | default `*` | `SetVaryByQuery("day")` | only `day` | | enabled | default policy | `NoCache()` | not cached | | tags | `Tag("lineup")` | `Tag("acts")` | both tags | Tags accumulate because they are added to a set, while scalar settings are overwritten. Query keys behave in between: the first `SetVaryByQuery` replaces the default `*`, and a later one appends its keys to the list. ## What a policy can set Whether it is base, named or endpoint-level, a builder-made policy is assembled from the same `OutputCachePolicyBuilder` methods: | Method | Effect on the request's context | |---|---| | `Expire(TimeSpan)` | entry lifetime | | `Tag(params string[])` | labels for `EvictByTagAsync` | | `SetVaryByQuery`, `SetVaryByHeader`, `SetVaryByRouteValue`, `VaryByValue` | parts of the cache key | | `SetVaryByHost(bool)` | whether the host is in the key | | `SetCacheKeyPrefix(...)` | a fixed or computed key prefix | | `SetLocking(bool)` | request coalescing on a miss | | `With(predicate)` | apply the policy only when the predicate holds | | `NoCache()` / `Cache()` | switch output caching off or on | | `AddPolicy<T>()` | append a custom `IOutputCachePolicy` type | A custom class implementing `IOutputCachePolicy` can be passed directly to `AddBasePolicy(policy)`, `AddPolicy(name, policy)` or `CacheOutput(policy)` when the builder cannot express a rule. ## Opting one endpoint out With a base policy caching everything, an endpoint opts out with `.CacheOutput(b => b.NoCache())` or `[OutputCache(NoStore = true)]`. `NoCache()` clears the builder's own policies and adds one that sets `EnableOutputCaching = false`; because it runs after the base policies, nothing is looked up or stored. ## Traps interviewers probe - **`excludeDefaultPolicy: true`** removes the anonymous-GET-200 guard rails but also the flags that allow lookup and storage, so a builder policy made that way caches nothing on its own. - **`[OutputCache(PolicyName = ...)]`** deliberately skips adding the default policy, because the named policy already contains it. - A base policy that caches everything will also cache endpoints nobody reviewed; prefer named policies, or a `With` predicate, for anything not clearly public.

  • Why does a policy built with excludeDefaultPolicy: true and Cache() cache nothing?
    `Cache()` only adds a policy that sets `EnableOutputCaching = true`. The default policy is what sets `AllowCacheLookup` and `AllowCacheStorage` to `true` for eligible requests; without it both stay `false`, so the middleware neither looks up nor stores. A custom `IOutputCachePolicy` must set those flags itself.
  • Where should a typed policy registered with AddPolicy<T>() get scoped services such as a DbContext?
    Not from its constructor. The builder creates the instance once with `ActivatorUtilities` from the root provider and reuses it, so it behaves like a singleton. Resolve per-request services inside the callbacks from `context.HttpContext.RequestServices`.

  • Base policies run after endpoint policies, so the global setting always wins.
  • A named policy applies to every endpoint as soon as AddPolicy registers it.
  • An unknown policy name in CacheOutput throws at startup, so typos are caught.
  • [ResponseCache(NoStore = true)] stops a base output cache policy for that action.
  • Two Expire calls on one request combine by taking the shorter lifetime.