skip to content

In ASP.NET Core MVC, how do CacheProfiles work with [ResponseCache(CacheProfileName = ...)], and which value wins when the attribute and profile disagree?

level: middleimportance: should knowfreq 24%

answer

  1. MvcOptions.CacheProfiles dictionary
  2. names compared case-insensitively
  3. attribute property beats profile property
  4. unknown name: InvalidOperationException
  5. method-level filter replaces class-level

basics

~10 s

CacheProfiles is a named dictionary of CacheProfile settings on MvcOptions; [ResponseCache(CacheProfileName = "x")] uses it as defaults, and any property set on the attribute overrides the profile's. An unknown profile name throws InvalidOperationException.

solid answer

~50 s

You register profiles in `AddControllers(options => options.CacheProfiles.Add("Timetable", new CacheProfile { Duration = 300, VaryByQueryKeys = new[] { "route" } }))`; the dictionary compares names case-insensitively. `[ResponseCache(CacheProfileName = "Timetable")]` reads that profile when the filter is created and merges it property by property: anything set on the attribute wins, anything left unset comes from the profile. So `[ResponseCache(CacheProfileName = "Timetable", Duration = 60)]` writes `max-age=60` but keeps the profile's query keys. A name that is not registered throws `InvalidOperationException` ("The 'x' cache profile is not defined.") the first time the action's filters are built. When a controller class and an action both carry `[ResponseCache]`, the action's filter is the effective one and the class-level filter is skipped, so the two are not merged. Profiles exist for MVC and Razor Pages only; Minimal APIs and output caching have their own mechanisms.

code

csharp · 12 lines
csharp
builder.Services.AddControllers(o =>
    o.CacheProfiles.Add("Timetable", new CacheProfile
    {
        Duration = 300,
        VaryByQueryKeys = new[] { "route", "day" }
    }));

[ResponseCache(CacheProfileName = "Timetable")]            // public,max-age=300
public Task<Timetable?> Get(string route, string? day) => store.FindAsync(route, day);

[ResponseCache(CacheProfileName = "timetable", Duration = 60)] // public,max-age=60, same query keys
public Task<Timetable?> Today(string route) => store.FindAsync(route, null);

go deeper

for a junior

Know that CacheProfiles are named [ResponseCache] settings registered on MvcOptions and referenced with CacheProfileName.

for a middle

Explain the property-by-property merge where the attribute wins, the case-insensitive lookup, and the exception for an unknown name.

for a senior

Call out that unknown names fail on first request rather than startup, that method-level filters replace class-level ones without merging, and that Razor Pages and Minimal APIs need other routes.

for a principal

Use profiles as the organisation's catalogue of HTTP caching policies, with tests and configuration ownership, so per-action attributes stay rare.

## What a cache profile is A **cache profile** is a named, reusable set of `[ResponseCache]` settings. The type is `CacheProfile` in `Microsoft.AspNetCore.Mvc`, with the same five properties as the attribute, all nullable: - `int? Duration` - `ResponseCacheLocation? Location` - `bool? NoStore` - `string? VaryByHeader` - `string[]? VaryByQueryKeys` Profiles live in **`MvcOptions.CacheProfiles`**, an `IDictionary<string, CacheProfile>` created with a case-insensitive comparer. They replace copy-pasted attribute arguments across dozens of actions with one place to change a policy. ## Registering and using profiles For the bus network's timetable API: ```csharp builder.Services.AddControllers(options => { options.CacheProfiles.Add("Timetable", new CacheProfile { Duration = 300, VaryByQueryKeys = new[] { "route", "day" } }); options.CacheProfiles.Add("Never", new CacheProfile { NoStore = true, Location = ResponseCacheLocation.None }); }); ``` ```csharp [ResponseCache(CacheProfileName = "Timetable")] public Task<Timetable?> Get(string route, string? day) => ...; [ResponseCache(CacheProfileName = "Never")] public Task<Ticket> Purchase(...) => ...; ``` Because profile names are case-insensitive, `"timetable"` finds the same entry. ## How attribute and profile values merge When MVC builds the filter for an action, `ResponseCacheAttribute.GetCacheProfile` resolves the profile and merges **property by property**: | Property | Attribute sets it | Attribute leaves it unset | |---|---|---| | `Duration` | attribute value | profile value | | `Location` | attribute value | profile value, else `Any` | | `NoStore` | attribute value | profile value, else `false` | | `VaryByHeader` | attribute value | profile value | | `VaryByQueryKeys` | attribute value | profile value | So `[ResponseCache(CacheProfileName = "Timetable", Duration = 60)]` writes `public,max-age=60` and still varies by `route` and `day`. The attribute tracks "unset" with private nullable fields, which is why an explicit `NoStore = false` on the attribute does override a profile's `NoStore = true`. The usual header rules then apply to the merged result: if neither the attribute nor the profile supplies a `Duration`, and `NoStore` is not `true` and `Location` is not `None`, the filter throws when it runs. ## Failure modes 1. **Unknown profile name.** `GetCacheProfile` throws `InvalidOperationException` with "The 'Timetabel' cache profile is not defined." That happens when the filter is created, on the first request to the action, not at startup, so a typo in a rarely called action can sit unnoticed. 2. **Class plus method attributes.** If a controller has `[ResponseCache(CacheProfileName = "Timetable")]` and one action has its own `[ResponseCache(Duration = 10)]`, only the action's filter runs; MVC finds the most specific `IResponseCacheFilter` and skips the class-level one. The action does **not** inherit the class's `VaryByQueryKeys`. 3. **Global filters and Razor Pages.** Adding a `ResponseCacheAttribute` to `MvcOptions.Filters` applies it to controllers, but the docs note it does not apply to Razor Pages, which need a page filter convention. ## Where profiles do not reach - **Minimal APIs** never run MVC filters, so profiles are irrelevant there. - **Output caching** has its own named policies (`AddPolicy` with `CacheOutput("name")` or `[OutputCache(PolicyName = ...)]`); `CacheProfiles` does not feed it. ## Profiles compared with output cache policies Both features let you name a caching recipe once and reference it by name, which is why candidates confuse them: | | `MvcOptions.CacheProfiles` | Output cache `AddPolicy` | |---|---|---| | What the name selects | `Cache-Control`/`Vary` header settings | server-side caching rules | | Referenced by | `[ResponseCache(CacheProfileName = ...)]` | `CacheOutput("name")`, `[OutputCache(PolicyName = ...)]` | | Unknown name | throws `InvalidOperationException` | contributes nothing, silently | | Works with Minimal APIs | no | yes | An app can use both on the same action: the profile describes what browsers and CDNs may do, the output cache policy what the server does. ## Good practice - Name profiles after intent (`Timetable`, `Never`, `StaticReference`) rather than numbers, so changing five minutes to ten is one edit. - Keep a `NoStore` profile for error, checkout and account pages, and apply it explicitly. - Cover each profile name with a test that requests an action using it; that turns a typo's runtime exception into a failing build.

  • Can cache profiles be loaded from appsettings.json?
    Yes, indirectly: `CacheProfile` is a plain class with settable properties, so you can bind a configuration section to `CacheProfile` instances and add them to `options.CacheProfiles` inside `AddControllers`. The attribute still refers to them by name, so operators can retune durations without a rebuild.
  • Why might an action using [ResponseCache(CacheProfileName = "Timetable")] start throwing after someone edits the profile?
    If the edit removes `Duration` and leaves `NoStore` unset and `Location` other than `None`, the merged settings have no lifetime, and the filter throws `InvalidOperationException` asking for `Duration` on every request to that action.

  • A profile's values override whatever the attribute sets explicitly.
  • An unknown CacheProfileName silently falls back to no caching headers.
  • Profile names are case-sensitive, so "timetable" will not match "Timetable".
  • A method-level [ResponseCache] merges with the class-level one property by property.
  • CacheProfiles also configure the output cache's named policies.