ASP.NET Core 中的响应缓存中间件Response Caching Middleware in ASP.NET Core

作者:John LuoBy John Luo

本文介绍如何在 ASP.NET Core 应用程序中配置响应缓存中间件。This article explains how to configure Response Caching Middleware in an ASP.NET Core app. 中间件确定响应何时可缓存、存储响应,并提供来自缓存的响应。The middleware determines when responses are cacheable, stores responses, and serves responses from cache. 有关 HTTP 缓存和属性的介绍 [ResponseCache] ,请参阅 响应缓存For an introduction to HTTP caching and the [ResponseCache] attribute, see Response Caching.

查看或下载示例代码如何下载View or download sample code (how to download)

ConfigurationConfiguration

响应缓存中间件可通过共享框架隐式地用于 ASP.NET Core 应用。Response Caching Middleware is implicitly available for ASP.NET Core apps via the shared framework.

在中 Startup.ConfigureServices ,将响应缓存中间件添加到服务集合:In Startup.ConfigureServices, add the Response Caching Middleware to the service collection:

public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCaching();
    services.AddRazorPages();
}

将应用程序配置为将中间件与 UseResponseCaching 扩展方法一起使用,该扩展方法将中间件添加到中的请求处理管道 Startup.ConfigureConfigure the app to use the middleware with the UseResponseCaching extension method, which adds the middleware to the request processing pipeline in Startup.Configure:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
    }

    app.UseStaticFiles();
    app.UseRouting();
    // UseCors must be called before UseResponseCaching
    // app.UseCors("myAllowSpecificOrigins");

    app.UseResponseCaching();

    app.Use(async (context, next) =>
    {
        context.Response.GetTypedHeaders().CacheControl = 
            new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
            {
                Public = true,
                MaxAge = TimeSpan.FromSeconds(10)
            };
        context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] = 
            new string[] { "Accept-Encoding" };

        await next();
    });

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

警告

UseCorsUseResponseCaching使用CORS 中间件之前,必须先调用。UseCors must be called before UseResponseCaching when using CORS middleware.

示例应用添加标头以在后续请求时控制缓存:The sample app adds headers to control caching on subsequent requests:

  • 缓存控制:将可缓存的响应缓存多达10秒。Cache-Control: Caches cacheable responses for up to 10 seconds.
  • Vary:仅当后续请求的接受编码标头与原始请求的 接受编码 标头匹配时,才将中间件配置为提供缓存的响应。Vary: Configures the middleware to serve a cached response only if the Accept-Encoding header of subsequent requests matches that of the original request.
// using Microsoft.AspNetCore.Http;

app.Use(async (context, next) =>
{
    context.Response.GetTypedHeaders().CacheControl = 
        new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
        {
            Public = true,
            MaxAge = TimeSpan.FromSeconds(10)
        };
    context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] = 
        new string[] { "Accept-Encoding" };

    await next();
});

前面的标头不会写入响应,并在控制器、操作或页上被重写 Razor :The preceding headers are not written to the response and are overridden when a controller, action, or Razor Page:

  • 具有 [ResponseCache] 属性。Has a [ResponseCache] attribute. 即使未设置属性,这也适用。This applies even if a property isn't set. 例如,省略 VaryByHeader 属性将导致从响应中删除相应的标头。For example, omitting the VaryByHeader property will cause the corresponding header to be removed from the response.

响应缓存中间件仅缓存服务器响应,导致 200 (正常) 状态代码。Response Caching Middleware only caches server responses that result in a 200 (OK) status code. 中间件将忽略任何其他响应,包括 错误页Any other responses, including error pages, are 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

响应缓存选项如下表中所示。Response caching options are shown in the following table.

选项Option 说明Description
MaximumBodySize 响应正文的最大可缓存大小(以字节为单位)。The largest cacheable size for the response body in bytes. 默认值为 64 * 1024 * 1024 (64 MB) 。The default value is 64 * 1024 * 1024 (64 MB).
SizeLimit 响应缓存中间件的大小限制(以字节为单位)。The size limit for the response cache middleware in bytes. 默认值为 100 * 1024 * 1024 (100 MB) 。The default value is 100 * 1024 * 1024 (100 MB).
UseCaseSensitivePaths 确定是否将响应缓存在区分大小写的路径上。Determines if responses are cached on case-sensitive paths. 默认值为 falseThe default value is false.

下面的示例将中间件配置为:The following example configures the middleware to:

  • 大小小于或等于1024字节的缓存响应。Cache responses with a body size smaller than or equal to 1,024 bytes.
  • 将响应存储为区分大小写的路径。Store the responses by case-sensitive paths. 例如, /page1/Page1 分别存储。For example, /page1 and /Page1 are stored separately.
services.AddResponseCaching(options =>
{
    options.MaximumBodySize = 1024;
    options.UseCaseSensitivePaths = true;
});

VaryByQueryKeysVaryByQueryKeys

使用 MVC/web API 控制器或 Razor 页面页面模型时, [ResponseCache] 属性指定为响应缓存设置适当的标头所需的参数。When using MVC / web API controllers or Razor Pages page models, the [ResponseCache] attribute specifies the parameters necessary for setting the appropriate headers for response caching. [ResponseCache]严格要求中间件的属性的唯一参数是 VaryByQueryKeys ,它不对应于实际 HTTP 标头。The only parameter of the [ResponseCache] attribute that strictly requires the middleware is VaryByQueryKeys, which doesn't correspond to an actual HTTP header. 有关详细信息,请参阅 ASP.NET Core 中的响应缓存For more information, see ASP.NET Core 中的响应缓存.

如果不使用 [ResponseCache] 属性,响应缓存可能会随而变化 VaryByQueryKeysWhen not using the [ResponseCache] attribute, response caching can be varied with VaryByQueryKeys. ResponseCachingFeature直接从HttpContext使用:Use the ResponseCachingFeature directly from the HttpContext.Features:

var responseCachingFeature = context.HttpContext.Features.Get<IResponseCachingFeature>();

if (responseCachingFeature != null)
{
    responseCachingFeature.VaryByQueryKeys = new[] { "MyKey" };
}

使用等于中的单个值 *VaryByQueryKeys 根据所有请求查询参数改变缓存。Using a single value equal to * in VaryByQueryKeys varies the cache by all request query parameters.

响应缓存中间件使用的 HTTP 标头HTTP headers used by Response Caching Middleware

下表提供了有关影响响应缓存的 HTTP 标头的信息。The following table provides information on HTTP headers that affect response caching.

标头Header 详细信息Details
Authorization 如果标头存在,则不会缓存响应。The response isn't cached if the header exists.
Cache-Control 中间件仅考虑用缓存指令标记的缓存响应 publicThe middleware only considers caching responses marked with the public cache directive. 具有以下参数的控件缓存:Control caching with the following parameters:
  • 最大期限max-age
  • 最大过期†max-stale†
  • 最小-新min-fresh
  • must-revalidatemust-revalidate
  • no-cacheno-cache
  • 无-商店no-store
  • 仅限-缓存only-if-cached
  • privateprivate
  • 公共public
  • s-maxages-maxage
  • 代理重新验证‡proxy-revalidate‡
†如果未指定任何限制 max-stale ,则中间件不会执行任何操作。†If no limit is specified to max-stale, the middleware takes no action.
proxy-revalidate 的效果与相同 must-revalidateproxy-revalidate has the same effect as must-revalidate.

有关详细信息,请参阅 RFC 7231: Request Cache-Control 指令For more information, see RFC 7231: Request Cache-Control Directives.
Pragma Pragma: no-cache请求中的标头将产生与相同的效果 Cache-Control: no-cacheA Pragma: no-cache header in the request produces the same effect as Cache-Control: no-cache. 标头中的相关指令 Cache-Control (如果存在)将重写此标头。This header is overridden by the relevant directives in the Cache-Control header, if present. 考虑向后兼容 HTTP/1.0。Considered for backward compatibility with HTTP/1.0.
Set-Cookie 如果标头存在,则不会缓存响应。The response isn't cached if the header exists. 请求处理管道中设置一个或多个的任何中间件 cookie 会阻止响应缓存中间件缓存响应 (例如, cookie 基于的 TempData 提供程序) 。Any middleware in the request processing pipeline that sets one or more cookies prevents the Response Caching Middleware from caching the response (for example, the cookie-based TempData provider).
Vary Vary标头用于根据另一个标头改变缓存的响应。The Vary header is used to vary the cached response by another header. 例如,通过包含标头来缓存响应, Vary: Accept-Encoding 此标头将使用标头和单独的请求来缓存响应 Accept-Encoding: gzip Accept-Encoding: text/plainFor example, cache responses by encoding by including the Vary: Accept-Encoding header, which caches responses for requests with headers Accept-Encoding: gzip and Accept-Encoding: text/plain separately. 永远不会存储标头值 * 为的响应。A response with a header value of * is never stored.
Expires 除非由其他标头重写,否则不会存储或检索此标头过时的响应 Cache-ControlA response deemed stale by this header isn't stored or retrieved unless overridden by other Cache-Control headers.
If-None-Match 如果值不为 * ,并且响应的与提供的任何值都不匹配,则将从缓存中提供完整响应 ETagThe full response is served from cache if the value isn't * and the ETag of the response doesn't match any of the values provided. 否则,将为 304 (修改) 响应。Otherwise, a 304 (Not Modified) response is served.
If-Modified-Since 如果 If-None-Match 标头不存在,则在缓存的响应日期比提供的值更新时,将从缓存中提供完整响应。If the If-None-Match header isn't present, a full response is served from cache if the cached response date is newer than the value provided. 否则,将提供 304-未修改 响应。Otherwise, a 304 - Not Modified response is served.
Date 从缓存提供时, Date 如果未在原始响应中提供标头,中间件将设置标头。When serving from cache, the Date header is set by the middleware if it wasn't provided on the original response.
Content-Length 从缓存提供时, Content-Length 如果未在原始响应中提供标头,中间件将设置标头。When serving from cache, the Content-Length header is set by the middleware if it wasn't provided on the original response.
Age Age忽略原始响应中发送的标头。The Age header sent in the original response is ignored. 中间件在为缓存的响应提供服务时计算一个新值。The middleware computes a new value when serving a cached response.

缓存遵从请求 Cache-Control 指令Caching respects request Cache-Control directives

中间件遵循 HTTP 1.1 缓存规范的规则。The middleware respects the rules of the HTTP 1.1 Caching specification. 规则要求使用缓存来服从 Cache-Control 客户端发送的有效标头。The rules require a cache to honor a valid Cache-Control header sent by the client. 在规范下,客户端可以使用 no-cache 标头值发出请求,并强制服务器为每个请求生成新的响应。Under the specification, a client can make requests with a no-cache header value and force the server to generate a new response for every request. 目前,在使用中间件时,不存在对此缓存行为的开发人员控制,因为中间件遵循官方缓存规范。Currently, there's no developer control over this caching behavior when using the middleware because the middleware adheres to the official caching specification.

为了更好地控制缓存行为,浏览 ASP.NET Core 的其他缓存功能。For more control over caching behavior, explore other caching features of ASP.NET Core. 请参阅下列主题:See the following topics:

疑难解答Troubleshooting

如果缓存行为与预期不符,请确认响应是可缓存的并且能够通过缓存提供服务。If caching behavior isn't as expected, confirm that responses are cacheable and capable of being served from the cache. 检查请求的传入标头和响应的传出标头。Examine the request's incoming headers and the response's outgoing headers. 启用 日志记录 以帮助进行调试。Enable logging to help with debugging.

在对缓存行为进行测试和故障排除时,浏览器可能会以不需要的方式设置影响缓存的请求标头。When testing and troubleshooting caching behavior, a browser may set request headers that affect caching in undesirable ways. 例如,浏览器可以在 Cache-Control no-cache 刷新页面时将标题设置为或 max-age=0For example, a browser may set the Cache-Control header to no-cache or max-age=0 when refreshing a page. 以下工具可以显式设置请求标头,并优先于测试缓存:The following tools can explicitly set request headers and are preferred for testing caching:

缓存条件Conditions for caching

  • 请求必须使用 200 (良好) 状态代码来生成服务器响应。The request must result in a server response with a 200 (OK) status code.
  • 请求方法必须为 GET 或 HEAD。The request method must be GET or HEAD.
  • 在中 Startup.Configure ,必须将响应缓存中间件置于需要缓存的中间件之前。In Startup.Configure, Response Caching Middleware must be placed before middleware that require caching. 有关详细信息,请参阅 ASP.NET Core 中间件For more information, see ASP.NET Core 中间件.
  • Authorization标题不得存在。The Authorization header must not be present.
  • Cache-Control 标头参数必须是有效的,并且响应必须标记 public 且未标记 privateCache-Control header parameters must be valid, and the response must be marked public and not marked private.
  • Pragma: no-cache如果标头不存在,则标头不得出现 Cache-Control ,因为标头会 Cache-Control Pragma 在存在时覆盖标头。The Pragma: no-cache header must not be present if the Cache-Control header isn't present, as the Cache-Control header overrides the Pragma header when present.
  • Set-Cookie标题不得存在。The Set-Cookie header must not be present.
  • Vary 标头参数必须有效并且不等于 *Vary header parameters must be valid and not equal to *.
  • Content-Length如果设置) 必须与响应正文的大小匹配,则标头值 (。The Content-Length header value (if set) must match the size of the response body.
  • IHttpSendFileFeature不使用。The IHttpSendFileFeature isn't used.
  • Expires标头和 max-age 和缓存指令指定的响应不能过时 s-maxageThe response must not be stale as specified by the Expires header and the max-age and s-maxage cache directives.
  • 响应缓冲必须成功。Response buffering must be successful. 响应的大小必须小于配置的或默认值 SizeLimitThe size of the response must be smaller than the configured or default SizeLimit. 响应的正文大小必须小于配置的或默认值 MaximumBodySizeThe body size of the response must be smaller than the configured or default MaximumBodySize.
  • 必须根据 RFC 7234 规范来缓存响应。The response must be cacheable according to the RFC 7234 specifications. 例如, no-store 指令在请求或响应标头字段中不得存在。For example, the no-store directive must not exist in request or response header fields. 有关详细信息,请参阅 第3部分:将响应存储在 RFC 7234 的缓存中。See Section 3: Storing Responses in Caches of RFC 7234 for details.

备注

用于生成安全令牌的防伪系统,以防止跨站点请求伪造 (CSRF) 攻击将 Cache-ControlPragma 标头设置为, no-cache 以便不缓存响应。The Antiforgery system for generating secure tokens to prevent Cross-Site Request Forgery (CSRF) attacks sets the Cache-Control and Pragma headers to no-cache so that responses aren't cached. 有关如何为 HTML 窗体元素禁用防伪标记的信息,请参阅 阻止跨站点请求伪造 (XSRF/CSRF) 攻击 ASP.NET CoreFor information on how to disable antiforgery tokens for HTML form elements, see 阻止跨站点请求伪造 (XSRF/CSRF) 攻击 ASP.NET Core.

其他资源Additional resources

本文介绍如何在 ASP.NET Core 应用程序中配置响应缓存中间件。This article explains how to configure Response Caching Middleware in an ASP.NET Core app. 中间件确定响应何时可缓存、存储响应,并提供来自缓存的响应。The middleware determines when responses are cacheable, stores responses, and serves responses from cache. 有关 HTTP 缓存和属性的介绍 [ResponseCache] ,请参阅 响应缓存For an introduction to HTTP caching and the [ResponseCache] attribute, see Response Caching.

查看或下载示例代码如何下载View or download sample code (how to download)

ConfigurationConfiguration

使用 AspNetCore 元包 或添加对 AspNetCore. ResponseCaching 包的包引用。Use the Microsoft.AspNetCore.App metapackage or add a package reference to the Microsoft.AspNetCore.ResponseCaching package.

在中 Startup.ConfigureServices ,将响应缓存中间件添加到服务集合:In Startup.ConfigureServices, add the Response Caching Middleware to the service collection:

public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCaching();
    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

将应用程序配置为将中间件与 UseResponseCaching 扩展方法一起使用,该扩展方法将中间件添加到中的请求处理管道 Startup.ConfigureConfigure the app to use the middleware with the UseResponseCaching extension method, which adds the middleware to the request processing pipeline in Startup.Configure:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
    }

    app.UseStaticFiles();

    app.UseResponseCaching();

    app.Use(async (context, next) =>
    {
        context.Response.GetTypedHeaders().CacheControl = 
            new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
            {
                Public = true,
                MaxAge = TimeSpan.FromSeconds(10)
            };
        context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] = 
            new string[] { "Accept-Encoding" };

        await next();
    });

    app.UseMvc();
}

示例应用添加标头以在后续请求时控制缓存:The sample app adds headers to control caching on subsequent requests:

  • 缓存控制:将可缓存的响应缓存多达10秒。Cache-Control: Caches cacheable responses for up to 10 seconds.
  • Vary:仅当后续请求的接受编码标头与原始请求的 接受编码 标头匹配时,才将中间件配置为提供缓存的响应。Vary: Configures the middleware to serve a cached response only if the Accept-Encoding header of subsequent requests matches that of the original request.
// using Microsoft.AspNetCore.Http;

app.Use(async (context, next) =>
{
    context.Response.GetTypedHeaders().CacheControl = 
        new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
        {
            Public = true,
            MaxAge = TimeSpan.FromSeconds(10)
        };
    context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] = 
        new string[] { "Accept-Encoding" };

    await next();
});

前面的标头不会写入响应,并在控制器、操作或页上被重写 Razor :The preceding headers are not written to the response and are overridden when a controller, action, or Razor Page:

  • 具有 [ResponseCache] 属性。Has a [ResponseCache] attribute. 即使未设置属性,这也适用。This applies even if a property isn't set. 例如,省略 VaryByHeader 属性将导致从响应中删除相应的标头。For example, omitting the VaryByHeader property will cause the corresponding header to be removed from the response.

响应缓存中间件仅缓存服务器响应,导致 200 (正常) 状态代码。Response Caching Middleware only caches server responses that result in a 200 (OK) status code. 中间件将忽略任何其他响应,包括 错误页Any other responses, including error pages, are 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

响应缓存选项如下表中所示。Response caching options are shown in the following table.

选项Option 说明Description
MaximumBodySize 响应正文的最大可缓存大小(以字节为单位)。The largest cacheable size for the response body in bytes. 默认值为 64 * 1024 * 1024 (64 MB) 。The default value is 64 * 1024 * 1024 (64 MB).
SizeLimit 响应缓存中间件的大小限制(以字节为单位)。The size limit for the response cache middleware in bytes. 默认值为 100 * 1024 * 1024 (100 MB) 。The default value is 100 * 1024 * 1024 (100 MB).
UseCaseSensitivePaths 确定是否将响应缓存在区分大小写的路径上。Determines if responses are cached on case-sensitive paths. 默认值为 falseThe default value is false.

下面的示例将中间件配置为:The following example configures the middleware to:

  • 大小小于或等于1024字节的缓存响应。Cache responses with a body size smaller than or equal to 1,024 bytes.
  • 将响应存储为区分大小写的路径。Store the responses by case-sensitive paths. 例如, /page1/Page1 分别存储。For example, /page1 and /Page1 are stored separately.
services.AddResponseCaching(options =>
{
    options.MaximumBodySize = 1024;
    options.UseCaseSensitivePaths = true;
});

VaryByQueryKeysVaryByQueryKeys

使用 MVC/web API 控制器或 Razor 页面页面模型时, [ResponseCache] 属性指定为响应缓存设置适当的标头所需的参数。When using MVC / web API controllers or Razor Pages page models, the [ResponseCache] attribute specifies the parameters necessary for setting the appropriate headers for response caching. [ResponseCache]严格要求中间件的属性的唯一参数是 VaryByQueryKeys ,它不对应于实际 HTTP 标头。The only parameter of the [ResponseCache] attribute that strictly requires the middleware is VaryByQueryKeys, which doesn't correspond to an actual HTTP header. 有关详细信息,请参阅 ASP.NET Core 中的响应缓存For more information, see ASP.NET Core 中的响应缓存.

如果不使用 [ResponseCache] 属性,响应缓存可能会随而变化 VaryByQueryKeysWhen not using the [ResponseCache] attribute, response caching can be varied with VaryByQueryKeys. ResponseCachingFeature直接从HttpContext使用:Use the ResponseCachingFeature directly from the HttpContext.Features:

var responseCachingFeature = context.HttpContext.Features.Get<IResponseCachingFeature>();

if (responseCachingFeature != null)
{
    responseCachingFeature.VaryByQueryKeys = new[] { "MyKey" };
}

使用等于中的单个值 *VaryByQueryKeys 根据所有请求查询参数改变缓存。Using a single value equal to * in VaryByQueryKeys varies the cache by all request query parameters.

响应缓存中间件使用的 HTTP 标头HTTP headers used by Response Caching Middleware

下表提供了有关影响响应缓存的 HTTP 标头的信息。The following table provides information on HTTP headers that affect response caching.

标头Header 详细信息Details
Authorization 如果标头存在,则不会缓存响应。The response isn't cached if the header exists.
Cache-Control 中间件仅考虑用缓存指令标记的缓存响应 publicThe middleware only considers caching responses marked with the public cache directive. 具有以下参数的控件缓存:Control caching with the following parameters:
  • 最大期限max-age
  • 最大过期†max-stale†
  • 最小-新min-fresh
  • must-revalidatemust-revalidate
  • no-cacheno-cache
  • 无-商店no-store
  • 仅限-缓存only-if-cached
  • privateprivate
  • 公共public
  • s-maxages-maxage
  • 代理重新验证‡proxy-revalidate‡
†如果未指定任何限制 max-stale ,则中间件不会执行任何操作。†If no limit is specified to max-stale, the middleware takes no action.
proxy-revalidate 的效果与相同 must-revalidateproxy-revalidate has the same effect as must-revalidate.

有关详细信息,请参阅 RFC 7231: Request Cache-Control 指令For more information, see RFC 7231: Request Cache-Control Directives.
Pragma Pragma: no-cache请求中的标头将产生与相同的效果 Cache-Control: no-cacheA Pragma: no-cache header in the request produces the same effect as Cache-Control: no-cache. 标头中的相关指令 Cache-Control (如果存在)将重写此标头。This header is overridden by the relevant directives in the Cache-Control header, if present. 考虑向后兼容 HTTP/1.0。Considered for backward compatibility with HTTP/1.0.
Set-Cookie 如果标头存在,则不会缓存响应。The response isn't cached if the header exists. 请求处理管道中设置一个或多个的任何中间件 cookie 会阻止响应缓存中间件缓存响应 (例如, cookie 基于的 TempData 提供程序) 。Any middleware in the request processing pipeline that sets one or more cookies prevents the Response Caching Middleware from caching the response (for example, the cookie-based TempData provider).
Vary Vary标头用于根据另一个标头改变缓存的响应。The Vary header is used to vary the cached response by another header. 例如,通过包含标头来缓存响应, Vary: Accept-Encoding 此标头将使用标头和单独的请求来缓存响应 Accept-Encoding: gzip Accept-Encoding: text/plainFor example, cache responses by encoding by including the Vary: Accept-Encoding header, which caches responses for requests with headers Accept-Encoding: gzip and Accept-Encoding: text/plain separately. 永远不会存储标头值 * 为的响应。A response with a header value of * is never stored.
Expires 除非由其他标头重写,否则不会存储或检索此标头过时的响应 Cache-ControlA response deemed stale by this header isn't stored or retrieved unless overridden by other Cache-Control headers.
If-None-Match 如果值不为 * ,并且响应的与提供的任何值都不匹配,则将从缓存中提供完整响应 ETagThe full response is served from cache if the value isn't * and the ETag of the response doesn't match any of the values provided. 否则,将为 304 (修改) 响应。Otherwise, a 304 (Not Modified) response is served.
If-Modified-Since 如果 If-None-Match 标头不存在,则在缓存的响应日期比提供的值更新时,将从缓存中提供完整响应。If the If-None-Match header isn't present, a full response is served from cache if the cached response date is newer than the value provided. 否则,将提供 304-未修改 响应。Otherwise, a 304 - Not Modified response is served.
Date 从缓存提供时, Date 如果未在原始响应中提供标头,中间件将设置标头。When serving from cache, the Date header is set by the middleware if it wasn't provided on the original response.
Content-Length 从缓存提供时, Content-Length 如果未在原始响应中提供标头,中间件将设置标头。When serving from cache, the Content-Length header is set by the middleware if it wasn't provided on the original response.
Age Age忽略原始响应中发送的标头。The Age header sent in the original response is ignored. 中间件在为缓存的响应提供服务时计算一个新值。The middleware computes a new value when serving a cached response.

缓存遵从请求 Cache-Control 指令Caching respects request Cache-Control directives

中间件遵循 HTTP 1.1 缓存规范的规则。The middleware respects the rules of the HTTP 1.1 Caching specification. 规则要求使用缓存来服从 Cache-Control 客户端发送的有效标头。The rules require a cache to honor a valid Cache-Control header sent by the client. 在规范下,客户端可以使用 no-cache 标头值发出请求,并强制服务器为每个请求生成新的响应。Under the specification, a client can make requests with a no-cache header value and force the server to generate a new response for every request. 目前,在使用中间件时,不存在对此缓存行为的开发人员控制,因为中间件遵循官方缓存规范。Currently, there's no developer control over this caching behavior when using the middleware because the middleware adheres to the official caching specification.

为了更好地控制缓存行为,浏览 ASP.NET Core 的其他缓存功能。For more control over caching behavior, explore other caching features of ASP.NET Core. 请参阅下列主题:See the following topics:

疑难解答Troubleshooting

如果缓存行为与预期不符,请确认响应是可缓存的并且能够通过缓存提供服务。If caching behavior isn't as expected, confirm that responses are cacheable and capable of being served from the cache. 检查请求的传入标头和响应的传出标头。Examine the request's incoming headers and the response's outgoing headers. 启用 日志记录 以帮助进行调试。Enable logging to help with debugging.

在对缓存行为进行测试和故障排除时,浏览器可能会以不需要的方式设置影响缓存的请求标头。When testing and troubleshooting caching behavior, a browser may set request headers that affect caching in undesirable ways. 例如,浏览器可以在 Cache-Control no-cache 刷新页面时将标题设置为或 max-age=0For example, a browser may set the Cache-Control header to no-cache or max-age=0 when refreshing a page. 以下工具可以显式设置请求标头,并优先于测试缓存:The following tools can explicitly set request headers and are preferred for testing caching:

缓存条件Conditions for caching

  • 请求必须使用 200 (良好) 状态代码来生成服务器响应。The request must result in a server response with a 200 (OK) status code.
  • 请求方法必须为 GET 或 HEAD。The request method must be GET or HEAD.
  • 在中 Startup.Configure ,必须将响应缓存中间件置于需要缓存的中间件之前。In Startup.Configure, Response Caching Middleware must be placed before middleware that require caching. 有关详细信息,请参阅 ASP.NET Core 中间件For more information, see ASP.NET Core 中间件.
  • Authorization标题不得存在。The Authorization header must not be present.
  • Cache-Control 标头参数必须是有效的,并且响应必须标记 public 且未标记 privateCache-Control header parameters must be valid, and the response must be marked public and not marked private.
  • Pragma: no-cache如果标头不存在,则标头不得出现 Cache-Control ,因为标头会 Cache-Control Pragma 在存在时覆盖标头。The Pragma: no-cache header must not be present if the Cache-Control header isn't present, as the Cache-Control header overrides the Pragma header when present.
  • Set-Cookie标题不得存在。The Set-Cookie header must not be present.
  • Vary 标头参数必须有效并且不等于 *Vary header parameters must be valid and not equal to *.
  • Content-Length如果设置) 必须与响应正文的大小匹配,则标头值 (。The Content-Length header value (if set) must match the size of the response body.
  • IHttpSendFileFeature不使用。The IHttpSendFileFeature isn't used.
  • Expires标头和 max-age 和缓存指令指定的响应不能过时 s-maxageThe response must not be stale as specified by the Expires header and the max-age and s-maxage cache directives.
  • 响应缓冲必须成功。Response buffering must be successful. 响应的大小必须小于配置的或默认值 SizeLimitThe size of the response must be smaller than the configured or default SizeLimit. 响应的正文大小必须小于配置的或默认值 MaximumBodySizeThe body size of the response must be smaller than the configured or default MaximumBodySize.
  • 必须根据 RFC 7234 规范来缓存响应。The response must be cacheable according to the RFC 7234 specifications. 例如, no-store 指令在请求或响应标头字段中不得存在。For example, the no-store directive must not exist in request or response header fields. 有关详细信息,请参阅 第3部分:将响应存储在 RFC 7234 的缓存中。See Section 3: Storing Responses in Caches of RFC 7234 for details.

备注

用于生成安全令牌的防伪系统,以防止跨站点请求伪造 (CSRF) 攻击将 Cache-ControlPragma 标头设置为, no-cache 以便不缓存响应。The Antiforgery system for generating secure tokens to prevent Cross-Site Request Forgery (CSRF) attacks sets the Cache-Control and Pragma headers to no-cache so that responses aren't cached. 有关如何为 HTML 窗体元素禁用防伪标记的信息,请参阅 阻止跨站点请求伪造 (XSRF/CSRF) 攻击 ASP.NET CoreFor information on how to disable antiforgery tokens for HTML form elements, see 阻止跨站点请求伪造 (XSRF/CSRF) 攻击 ASP.NET Core.

其他资源Additional resources