我想将整个页面缓存到ASP.NET Core 2.1 MVC Web应用程序中的分布式缓存(特别是Redis) . 当用户访问页面时,执行action方法和视图cshtml中的代码,并生成页面并将其发送给用户 . 我希望在请求结束时缓存此页面,以便当后续用户访问页面时,它应该从缓存中呈现,而不必在操作方法或视图中执行任何代码 . 更具体地说,我希望它可以在Redis中缓存 . 我熟悉如何在Web应用程序中存储Redis中的键值对,并且熟悉如何将页面的某些部分缓存到Redis,但我无法弄清楚如何将 entire 页面缓存到Redis .

我已成功使用 IDistributedCache 接口的Redis特定实现来将键值对存储到Redis . 这是通过安装Microsoft.Extensions.Caching.Redis.Core NuGet包并将以下语句添加到 ConfigureServices() 来实现的:

services.AddDistributedRedisCache(options =>
{
    options.Configuration = "localhost";
    options.InstanceName = "SampleInstance";
});

完成后,我能够将Redis IDistributedCache 实现依赖注入控制器,然后使用 _cache.GetStringAsync()_cache.SetStringAsync() 之类的语句来存储和检索Redis的键值对 . 我还可以在.cshtml页面中使用 <distributed-cache> 标记帮助程序来缓存视图的各个部分 .

However these techniques do not help me to cache the entire page, only parts of it. 操作和视图中的代码仍然需要执行,页面需要重新渲染,尽管速度较快,因为其中一些是缓存的 . 我想要做的是缓存整个页面,以便可以从缓存中提供所有内容,而无需在action方法和视图cshtml中执行代码 .

我也知道如何使用内置功能在ASP Core 2.1中完成基本页面缓存 . 所有需要做的是在action方法中添加一个 [ResponseCaching(Duration=...)] 属性,在Startup.cs中分别添加语句 services.AddResponseCaching()app.UseResponseCaching()ConfigureServices()Configure() . Unfortunately, the page gets cached on the server instance, presumably in the server's memory. 我无法弄清楚如何告诉它在Redis中缓存此页面 .

基本上我想要像 [ResponseCaching(Duration=..., CACHE=REDIS)] 这样的东西 . 如何实现这一目标?


Old ASP.NET 4 Equivalent

在ASP.NET 4中,只需向操作添加 [OutputCache(Duration=...)] 属性,安装Microsoft.Web.RedisOutputCacheProvider NuGet包,并将以下内容放在web.config中

<caching>
    <outputCache defaultProvider="MyRedisOutputCache">
       <providers>
          <add name="MyRedisOutputCache" type=... host="" ssl="true" />
       </providers>
    </outputCache>
</caching>

然后整个页面将被缓存到Redis . 这很简单 . 这正是我试图在ASP Core 2.1中复制的功能 .