要解决ASP.NET Core 3响应缓存未按预期工作的问题,您可以尝试以下解决方法:
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCaching();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseResponseCaching();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCaching(options =>
{
options.SizeLimit = 100;
options.UseCaseSensitivePaths = true;
options.MaximumBodySize = 1024;
});
}
[ResponseCache(Duration = 60)] // 缓存60秒
public IActionResult Index()
{
// ...
}
// 或者
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseResponseCaching();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
context.Response.GetTypedHeaders().CacheControl =
new CacheControlHeaderValue()
{
Public = true,
MaxAge = TimeSpan.FromSeconds(60)
};
await context.Response.WriteAsync("Hello World!");
});
});
}
public IActionResult Index()
{
Response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
Response.Headers.Add("Pragma", "no-cache");
Response.Headers.Add("Expires", "0");
// ...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseResponseCaching();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
var cache = context.RequestServices.GetService();
var cacheKey = "MyUniqueCacheKey";
if (!cache.TryGetValue(cacheKey, out string response))
{
response = "Hello World!";
cache.Set(cacheKey, response, TimeSpan.FromSeconds(60));
}
await context.Response.WriteAsync(response);
});
});
}
希望这些解决方法能帮助您解决ASP.NET Core 3响应缓存未按预期工作的问题。