ASP.NET Core中的Http缓存使用

Http响应缓存可减少客户端或代理对web服务器发出的请求数。响应缓存还减少了web服务器生成响应所需的工作量。响应缓存由Http请求中的header控制。

ASP.NET Core对其都有相应的实现,并不需要了解里面的工作细节,即可对其进行良好的控制。

了解Http缓存

Http协议中定义了许多缓存,但总体可以分为强缓存和协商缓存两类。

其中最有意思的要数no-cachemust-revalidate了,因为它们的表现都不是字面意义。

no-cache并不是字面上的不缓存,而是会一直服务端验证(真实意义很像字面上的must-revalidate)。

must-revalidate是只是为了给浏览器强调,缓存过期后,千万要遵守约定重新验证。

协商缓存

协商缓存是指缓存命中时,服务器返回Http状态码为304但无内容(Body),没命中时返回200有内容。

在要精细控制时,协商缓存比强缓存更有用,它有Last-ModifiedETag两种。

Last-Modified/If-Modify-Since(对比修改时间)

示例:

服务器:Last-Modified: Sat, 27 Jun 2015 16:48:38 GMT
客户端:If-Modified-Since: Sat, 27 Jun 2015 16:48:38 GMT

ETag/If-None-Match(对比校验码)

服务器:ETag: W/"0a0b8e05663d11:0"
客户端:If-None-Match: W/"0a0b8e05663d11:0"

清缓存要点

  1. F5刷新时,强缓存失效
  2. Ctrl+F5刷新时 强缓存和协商缓存都失效

ASP.NET Core的Http缓存

ASP.NET Core中提供了ResponseCacheAttribute来实现缓存,它的定义如下:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class ResponseCacheAttribute : Attribute, IFilterFactory, IFilterMetadata, IOrderedFilter
{
  public ResponseCacheAttribute();
  public string CacheProfileName { get; set; }
  public int Duration { get; set; }
  public bool IsReusable { get; }
  public ResponseCacheLocation Location { get; set; }
  public bool NoStore { get; set; }

  public int Order { get; set; }
  public string VaryByHeader { get; set; }
  public string[] VaryByQueryKeys { get; set; }
}

其中,ResponseCacheLocation定义了缓存的位置,是重点:

//   Determines the value for the "Cache-control" header in the response.
public enum ResponseCacheLocation
{
  //   Cached in both proxies and client. Sets "Cache-control" header to "public".
  Any = 0,
  //   Cached only in the client. Sets "Cache-control" header to "private".
  Client = 1,
  //   "Cache-control" and "Pragma" headers are set to "no-cache".
  None = 2
}

注意看源文件中的注释,Any表示Cache-Control: publicClient表示Cache-Control: privateNone表示Cache-Control: no-cache

注意ResponseCacheLocation并没有定义将缓存放到服务器的选项。

其中Duration表示缓存时间,单位为秒,它将翻译为max-age

另外可以通过VaryByHeaderVaryByQueryKeys来配置缓存要不要通过headerquery string来变化,其中VaryByHeader是通过Http协议中的Vary头来实现的,VaryByQueryKeys必须通过Middleware来实现。

不要误会,所有ResponseCacheAttribute的属性配置都不会在服务端缓存你的响应数据(虽然你可能有这种错觉),它和输出缓存不同,它没有状态,只用来做客户端强缓存。

如果不想缓存,则设置NoStore = true,它会设置cache-control: no-store,我们知道no-store的真实意思是不缓存。一般还会同时设置Location = ResponseCacheLocation.None,它会设置cache-control: no-cache(真实意思是表示一定会验证)。

注意单独设置Location = ResponseCacheLocation.None而不设置NoStore并不会有任何效果。

示例1

这是一个很典型的使用示例:

public class HomeController : Controller
{
  [ResponseCache(Duration = 3600, Location = ResponseCacheLocation.Client)]
  public IActionResult Data()
  {
    return Json(DateTime.Now);
  }
}

我定义了3600秒的缓存,并且cache-control应该为private,生成的Http缓存头可以通过如下C#代码来验证:

using var http = new HttpClient();
var resp1 = await http.GetAsync("https://localhost:55555/home/data");
Console.WriteLine(resp1.Headers.CacheControl.ToString());
Console.WriteLine(await resp1.Content.ReadAsStringAsync());

输入结果如下:

max-age=3600, private
"2020-03-07T21:35:01.5843686+08:00"

另外,ResponseCacheAttribute也可以定义在Controller级别上,表示整个Controller都受到缓存的影响。

CacheProfileName示例

另外,如果需要共用缓存配置,可以使用CacheProfileName,将缓存提前定义好,之后直接传入这个定义名即可使用:

.ConfigureServices(s =>
{
  s.AddControllers(o =>
  {
    o.CacheProfiles.Add("3500", new CacheProfile
    {
      Duration = 3500, 
      Location = ResponseCacheLocation.Client,
    });
  });
});

这样我就定义了一个名为3500的缓存,稍后在Controller中我只需传入CacheProfileName = 3500即可:

public class HomeController : Controller
{
  [ResponseCache(CacheProfileName = "3500")]
  public IActionResult Data()
  {
    return Json(DateTime.Now);
  }
}

总结

Http缓存分为强缓存和协商缓存,ASP.NET Core提供了便利的ResponseCacheAttribute实现了强缓存,还能通过Profile来批量配置多个缓存点。

ASP.NET MVC并没有提供协商缓存实现,因为这些多半和业务逻辑相关,需要自己写代码。静态文件是特例,Microsoft.AspNetCore.StaticFiles中提供有,因为静态文件的逻辑很清晰。

ASP.NET中的OutputCacheAttributeASP.NET Core中不复存在,取而代之的是app/services.AddResponseCaching(),这些和Http协议不相关。

有机会我会具体聊聊这些缓存。

到此这篇关于ASP.NET Core中的Http缓存使用的文章就介绍到这了,更多相关ASP.NET Core Http缓存内容请搜索来客网以前的文章或继续浏览下面的相关文章希望大家以后多多支持来客网!