.net5 mvc 项目使用 ResponseCache
1 在 Startup.cs 添加服务和配置中间件
在 Startup.cs 的 ConfigureServices 添加如下代码:
services.AddResponseCaching(options => { options.SizeLimit = 100 * 1024 * 1024; // 最大缓存尺寸,默认是 100 MB });
接着在 Startup.cs 的 Configure 方法中启用中间件
app.UseResponseCaching();
2 使用 ResponseCache
在控制器动作方法中使用,并在 reture View() 代码处打上断点
[ResponseCache(Duration = 600)] // 秒为单位 public IActionResult Index() { return View(); }
3 测试
在浏览器首次打开页面 https://localhost:44389/home/index ,命中断点;
然后在浏览器中 打开一个新标签页,重新访问 https://localhost:44389/home/index,不会命中断点(不走服务器,直接读取缓存内容)
4 Startup.cs 完整代码如下
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddResponseCaching(options => { options.SizeLimit = 100 * 1024 * 1024; // 最大缓存尺寸,默认是 100 MB }); services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseResponseCaching(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } }