.NET 7 API中[OutputCache]特性无法生效的问题排查与求助
.NET 7 REST API [OutputCache] 失效问题处理
问题背景
在从.NET 5升级到.NET 7的REST API项目中,配置[OutputCache]特性后,无论是否是未授权端点,缓存均不生效。已完成如下配置:
服务配置
services.AddOutputCache(options => { options.AddBasePolicy(builder => builder.Cache()); //移除该行也无效 });
初始中间件配置
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IApiVersionDescriptionProvider provider) { //app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()); app.UseCors(); app.UseAuthentication(); app.UseExceptionHandler("/Error"); app.UseIpRateLimiting(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); var pathBase = Configuration["APPL_PATH"]; if (pathBase == "/") pathBase = ""; if (!string.IsNullOrEmpty(pathBase)) { app.UsePathBase(pathBase); } ServiceProviderResolver.ServiceProvider = app.ApplicationServices; app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseOutputCache(); }
端点代码
[AllowAnonymous] [OutputCache(Duration = 99999)] [HttpGet] public async Task<IActionResult> GetAsync([FromQuery] Dto dto) => ReturnDataFromDataBase();
断点验证发现每次请求都会进入数据库查询方法,缓存未生效。尝试调整app.UseOutputCache()位置到最开头时缓存生效,但不符合官方文档要求的顺序;移到UseCors()和UseRouting()之后则失效。
未认证端点缓存解决方案
问题根源在于项目中保留了app.UseMvc(),且控制器继承自Controller(MVC控制器)而非ControllerBase(API控制器)。移除app.UseMvc()并调整中间件顺序后,未认证端点的缓存功能正常生效:
修正后的中间件配置
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IApiVersionDescriptionProvider provider) { app.UseIpRateLimiting(); var pathBase = Configuration["APPL_PATH"]; if (pathBase == "/") pathBase = ""; if (!string.IsNullOrEmpty(pathBase)) { app.UsePathBase(pathBase); } ServiceProviderResolver.ServiceProvider = app.ApplicationServices; app.UseHttpsRedirection(); app.UseRouting(); app.UseCors(); app.UseAuthentication(); app.UseAuthorization(); app.UseOutputCache(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
剩余问题
当前已解决未认证端点的缓存失效问题,但需要JWT认证的端点仍无法使用[OutputCache],需进一步排查。
内容的提问来源于stack exchange,提问作者Ezequiel Irigoyen
相关产品推荐
相关产品推荐

