Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
By Rick Anderson and Kirk Larkin
Response caching reduces the number of requests a client or proxy makes to a web server. Response caching also reduces the amount of work the web server performs to generate a response. Response caching is set in headers.
The ResponseCache attribute sets response caching headers. Clients and intermediate proxies should honor the headers for caching responses under the RFC 9111: HTTP Caching specification.
For server-side caching that follows the HTTP 1.1 Caching specification, use response caching middleware. The middleware can use the ResponseCacheAttribute properties to influence server-side caching behavior.
The response caching middleware enables the caching of server responses based on HTTP Cache-Control headers.
Caching behavior implements standard HTTP caching semantics.
Caching is based on HTTP cache headers similar to the method used by proxies.
This form of caching is useful for public GET or HEAD API requests from clients where the conditions for caching are satisfied.
For UI apps like Razor Pages, response caching isn't typically beneficial. Browsers commonly set request headers that prevent caching.
Output caching (available in .NET 7 and later) is a better approach for UI apps. In this scenario, the configuration determines what to cache independent of HTTP headers.
To test response caching, use Fiddler or another tool that can explicitly set request headers. Setting headers explicitly is preferred for testing caching. For more information, see Response caching middleware > Troubleshooting.
View or download sample code (how to download)
HTTP-based response caching
The RFC 9111: HTTP Caching specification describes how internet caches should behave. The primary HTTP header used for caching is Cache-Control, which is used to specify cache directives. The directives control caching behavior as requests make their way from clients to servers and responses make their way from servers back to clients. Requests and responses move through proxy servers, and proxy servers must also conform to the HTTP 1.1 Caching specification.
Common Cache-Control directives are shown in the following table.
| Directive | Action |
|---|---|
| public | A cache can store the response. |
| private | A shared cache must not store the response. A private cache can store and reuse the response. |
| max-age | The client doesn't accept a response whose age is greater than the specified number of seconds. Examples: max-age=60 (60 seconds), max-age=2592000 (one month) |
| no-cache | On requests: A cache must not use a stored response to satisfy the request. The origin server regenerates the response for the client, and the middleware updates the stored response in its cache. On responses: The response must not be used for a subsequent request without validation on the origin server. |
| no-store | On requests: A cache must not store the request. On responses: A cache must not store any part of the response. |
Other cache headers that play a role in caching are shown in the following table.
| Header | Function |
|---|---|
| Age | Provides an estimate of the amount of time in seconds since the response was generated or successfully validated at the origin server. |
| Expires | Specifies the time after which the response is considered stale. |
| Pragma | Exists for backwards compatibility with HTTP 1.0 caches for setting no-cache behavior. If the Cache-Control header is present, the Pragma header is ignored. |
| Vary | Specifies that a cached response must not be sent unless all of the Vary header fields match in both the cached response's original request and the new request. |
HTTP-based caching respects request Cache-Control directives
The RFC 9111: HTTP Caching (Section 5.2. Cache-Control) specification requires a cache to honor a valid Cache-Control header sent by the client. A client can make requests with a no-cache header value and force the server to generate a new response for every request.
Always honoring client Cache-Control request headers makes sense if you consider the goal of HTTP caching. Under the official specification, caching is meant to reduce the latency and network overhead of satisfying requests across a network of clients, proxies, and servers. It isn't necessarily a way to control the load on an origin server.
There's no developer control over this caching behavior when using the response caching middleware because the middleware adheres to the official caching specification. .NET 7 and later includes support for output caching to better control server load. For more information, see Output caching.
ResponseCache attribute
The ResponseCacheAttribute class specifies the parameters necessary for setting appropriate headers in response caching.
Warning
Disable caching for content that contains information for authenticated clients. Caching should only be enabled for content that doesn't change based on a user's identity or whether a user is signed in.
The VaryByQueryKeys property varies the stored response by the values of the given list of query keys. When a single value of the wildcard asterisk (*) is provided, the middleware varies responses by all request query string parameters.
Response caching middleware must be enabled to set the VaryByQueryKeys property. Otherwise, a runtime exception is thrown. There isn't a corresponding HTTP header for the VaryByQueryKeys property. The property is an HTTP feature handled by response caching middleware. For the middleware to serve a cached response, the query string and query string value must match a previous request. For example, consider the sequence of requests and results shown in the following table.
| Request | Returned from |
|---|---|
http://example.com?key1=value1 |
Server |
http://example.com?key1=value1 |
Middleware |
http://example.com?key1=NewValue |
Server |
The server returns the first request and the middleware caches the request. The middleware returns the second request because the query string matches the previous (first) request. The third request isn't in the middleware cache because the query string value doesn't match a previous request.
The ResponseCacheAttribute class is used to configure and create (via the IFilterFactory interface) a Microsoft.AspNetCore.Mvc.Internal.ResponseCacheFilter. The ResponseCacheFilter performs the work of updating the appropriate HTTP headers and features of the response. The filter:
- Removes any existing headers for
Vary,Cache-Control, andPragma. - Writes out the appropriate headers based on the properties set in the ResponseCacheAttribute.
- Updates the response caching HTTP feature if the VaryByQueryKeys property is set.
Vary header
This header is only written when the VaryByHeader property is set. The property is set to the Vary property's value. The following sample uses the VaryByHeader property:
[ApiController]
public class TimeController : ControllerBase
{
[Route("api/[controller]")]
[HttpGet]
[ResponseCache(VaryByHeader = "User-Agent", Duration = 30)]
public ContentResult GetTime() => Content(
DateTime.Now.Millisecond.ToString());
View the response headers with Fiddler or another tool. The response headers include:
Cache-Control: public,max-age=30
Vary: User-Agent
The preceding code requires adding the response caching middleware services AddResponseCaching method to the service collection. The code configures the app to use the middleware with the UseResponseCaching extension method.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddResponseCaching();
var app = builder.Build();
app.UseHttpsRedirection();
// UseCors must be called before UseResponseCaching
//app.UseCors();
app.UseResponseCaching();
app.UseAuthorization();
app.MapControllers();
app.Run();
NoStore and Location.None properties
The NoStore property overrides most of the other properties. When this property is set to true, the Cache-Control header is set to no-store. If the Location property is set to None:
- The
Cache-Controlheader is set tono-store,no-cache. - The
Pragmaheader is set tono-cache.
If the NoStore property is set to false and the Location property is set to None, the Cache-Control and Pragma headers are set to no-cache.
The NoStore property is typically set to true for error pages. The following code produces response headers that instruct the client not to store the response.
[Route("api/[controller]/ticks")]
[HttpGet]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public ContentResult GetTimeTicks() => Content(
DateTime.Now.Ticks.ToString());
The preceding code includes the following headers in the response:
Cache-Control: no-store,no-cache
Pragma: no-cache
To apply the ResponseCacheAttribute to all of the app's MVC controller or Razor Pages page responses, add the attribute with an MVC filter or Razor Pages filter.
In an MVC app, add the following code:
builder.Services.AddControllersWithViews().AddMvcOptions(options =>
options.Filters.Add(
new ResponseCacheAttribute
{
NoStore = true,
Location = ResponseCacheLocation.None
}));
For an approach that applies to Razor Pages apps, see GitHub dotnet/aspnetcore issue #18890) - Adding ResponseCacheAttribute to MVC global filter list does not apply to Razor Pages. The comment example in the issue applies to ASP.NET Core apps that predate the release of Minimal APIs (ASP.NET Core version 6.0). For apps that target version 6.0 and later, change the service registration used in the example to builder.Services.AddSingleton... in the Program.cs file.
Location and Duration properties
To enable caching, the Duration property must be set to a positive value and Location must be either Any (the default) or Client. The framework sets the Cache-Control header to the location value followed by the max-age of the response.
The Location property options of Any and Client translate into Cache-Control header values of public and private, respectively. As noted in the NoStore and Location.None section, setting the Location property to None sets both the Cache-Control and Pragma headers to no-cache.
The Location.Any (Cache-Control set to public) property setting indicates that the client or any intermediate proxy can cache the value, including response caching middleware.
The Location.Client (Cache-Control set to private) property setting indicates that only the client can cache the value. No intermediate cache should cache the value, including response caching middleware.
Cache control headers provide guidance to clients and intermediary proxies about when and how to cache responses. There's no guarantee that clients and proxies honor the RFC 9111: HTTP Caching specification. Response caching middleware always follows the caching rules laid out by the specification.
The following example shows the headers produced by setting the Duration property and leaving the default Location property value:
[Route("api/[controller]/ms")]
[HttpGet]
[ResponseCache(Duration = 10, Location = ResponseCacheLocation.Any, NoStore = false)]
public ContentResult GetTimeMS() => Content(
DateTime.Now.Millisecond.ToString());
The preceding code includes the following headers in the response:
Cache-Control: public,max-age=10
Cache profiles
Instead of duplicating response cache settings on many controller action attributes, cache profiles can be configured as options when setting up MVC pages or Razor Pages. Values found in a referenced cache profile are used as the defaults by the ResponseCacheAttribute. Any properties specified on the attribute override the referenced cache profile values.
The following example shows a 30-second cache profile:
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResponseCaching();
builder.Services.AddControllers(options =>
{
options.CacheProfiles.Add("Default30",
new CacheProfile()
{
Duration = 30
});
});
var app = builder.Build();
app.UseHttpsRedirection();
// UseCors must be called before UseResponseCaching
//app.UseCors();
app.UseResponseCaching();
app.UseAuthorization();
app.MapControllers();
app.Run();
The following code references the Default30 cache profile:
[ApiController]
[ResponseCache(CacheProfileName = "Default30")]
public class Time2Controller : ControllerBase
{
[Route("api/[controller]")]
[HttpGet]
public ContentResult GetTime() => Content(
DateTime.Now.Millisecond.ToString());
[Route("api/[controller]/ticks")]
[HttpGet]
public ContentResult GetTimeTicks() => Content(
DateTime.Now.Ticks.ToString());
}
The resulting header response by the Default30 cache profile includes:
Cache-Control: public,max-age=30
You can apply the [ResponseCache] attribute to Razor Pages, MVC controllers, and MVC action methods.
In Razor Pages, you can't apply attributes to handler methods because browsers used with UI apps prevent response caching. In an MVC action method, the method-level attributes override the settings specified in class-level attributes.
The following code applies the [ResponseCache] attribute at the controller level and method level:
[ApiController]
[ResponseCache(VaryByHeader = "User-Agent", Duration = 30)]
public class Time4Controller : ControllerBase
{
[Route("api/[controller]")]
[HttpGet]
public ContentResult GetTime() => Content(
DateTime.Now.Millisecond.ToString());
[Route("api/[controller]/ticks")]
[HttpGet]
public ContentResult GetTimeTicks() => Content(
DateTime.Now.Ticks.ToString());
[Route("api/[controller]/ms")]
[HttpGet]
[ResponseCache(Duration = 10, Location = ResponseCacheLocation.Any, NoStore = false)]
public ContentResult GetTimeMS() => Content(
DateTime.Now.Millisecond.ToString());
}
Related content
ASP.NET Core