Response Caching Middleware
By Luke Latham and John Luo
This document provides details on how to configure the Response Caching Middleware in ASP.NET Core applications. The middleware determines when responses are cacheable, stores responses, and serves responses from cache. For an introduction to HTTP caching and the ResponseCache
attribute, see Response Caching.
Package
To include the middleware in your project, add a reference to the Microsoft.AspNetCore.ResponseCaching
package. The middleware depends on .NET Framework 4.5.1 or .NET Standard 1.3 or later. This feature is available for apps that target ASP.NET Core 1.1.0 or later.
Configuration
In ConfgureServices
, add the middleware to your service collection.
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCaching();
}
Configure the application to use the middleware when processing requests. The sample application adds a Cache-Control
header to the response that will cache cacheable responses for up to 10 seconds. The sample also sends a Vary
header to configure the cache to serve the response only if the Accept-Encoding
header of subsequent requests matches that from the original request.
public void Configure(IApplicationBuilder app)
{
app.UseResponseCaching();
app.Run(async (context) =>
{
context.Response.GetTypedHeaders().CacheControl = new CacheControlHeaderValue()
{
Public = true,
MaxAge = TimeSpan.FromSeconds(10)
};
context.Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" };
await context.Response.WriteAsync("Hello World! " + DateTime.UtcNow);
});
}
The Response Caching Middleware only caches 200 (OK) server responses. Any other responses, including error pages, will be ignored by the middleware.
警告
Responses containing content for authenticated clients must be marked as not cacheable to prevent the middleware from storing and serving those responses. See Conditions for caching for details on how the middleware determines if a response is cacheable.
Options
The middleware offers two options for controlling response caching.
Option | Default Value |
---|---|
UseCaseSensitivePaths | Determines if responses will be cached on case-sensitive paths. The default value is |
MaximumBodySize | The largest cacheable size for the response body in bytes. The default value is64 * 1024 * 1024 [64 MB (67,108,864 bytes)]. |
The following example configures the middleware to cache responses smaller than or equal to 1,024 bytes using case-sensitive paths, storing the responses to /page1
and /Page1
separately.
services.AddResponseCaching(options =>
{
options.UseCaseSensitivePaths = true;
options.MaximumBodySize = 1024;
});
VaryByQueryKeys feature
When using MVC, the ResponseCache
attribute specifies the parameters necessary for setting appropriate headers for response caching. The only parameter of the ResponseCache
attribute that strictly requires the middleware is VaryByQueryKeys
, which does not correspond to an actual HTTP header. For more information, see ResponseCache Attribute.
When not using MVC, you can vary response caching with the VaryByQueryKeys
feature by using the ResponseCachingFeature
directly from the IFeatureCollection
of the HttpContext
.
var responseCachingFeature = context.HttpContext.Features.Get<IResponseCachingFeature>();
if (responseCachingFeature != null)
{
responseCachingFeature.VaryByQueryKeys = new[] { "MyKey" };
}
HTTP headers used by Response Caching Middleware
Response caching by the middleware is configured via your HTTP response headers. The relevant headers are listed below with notes on how they affect caching.
Header | Details |
---|---|
Authorization | The response is not cached if the header exists. |
Cache-Control | The middleware will only consider caching responses explicitly marked with the You can control caching with the following parameters:
For more information, see RFC 7231: Request Cache-Control Directives. |
Pragma | A Considered for backward compatibility with HTTP/1.0. |
Set-Cookie | The response is not cached if the header exists. |
Vary | You can vary the cached response by another header. For example, you can cache responses by encoding by including the |
Expires | A response deemed stale by this header will not be stored or retrieved unless overridden by other |
If-None-Match | The full response will be served from cache if the value is not |
If-Modified-Since | If the |
Date | When serving from cache, the |
Content-Length | When serving from cache, the |
Age | The |
Troubleshooting
If caching behavior is not as you expect, confirm that responses are cacheable and capable of being served from the cache by examining the request's incoming headers and the response's outgoing headers. The conditions by which a response will be cached are listed below.
Enabling logging can help when debugging. For example, the middleware logs why a response is or is not cached and whether it was retrieved from cache. See Logging in ASP.NET Core for more information on enabling logging in your application.
When testing and troubleshooting caching behavior, a browser may set request headers that affect caching in undesirable ways. For example, a browser may set the Cache-Control
header to no-cache
when you refresh the page. Instead of using a browser, use a tool like Fiddler, Firebug, or Postman, all of which allow you to explicitly set request headers.
Conditions for caching
- The request must result in a 200 (OK) response from the server.
- The request method must be GET or HEAD.
- Terminal middleware, such as Static File Middleware, must not process the response prior to the Response Caching Middleware.
- The
Authorization
header must not be present. Cache-Control
header parameters must be valid, and the response must be markedpublic
and not markedprivate
.- The
Pragma: no-cache
header/value must not be present if theCache-Control
header is not present, as theCache-Control
header overrides thePragma
header when present. - The
Set-Cookie
header must not be present. Vary
header parameters must be valid and not equal to*
.- The
Content-Length
header value (if set) must match the size of the response body. - The
HttpSendFileFeature
is not used. - The response must not be stale as specified by the
Expires
header and themax-age
ands-maxage
cache directives. - Response buffering is successful, and the total length of the response is smaller than the configured limit.
- The response must be cacheable according to the RFC 7234 specifications. For example, the
no-store
directive must not exist in request or response header fields. See Section 3: Storing Responses in Caches of the RFC document for details.
备注
The Antiforgery system for generating secure tokens to prevent Cross-Site Request Forgery (CSRF) attacks will set the Cache-Control
and Pragma
headers to no-cache
so that responses will not be cached.