我在asp.net核心工作。我面临一个问题,即当我通过浏览器后退按钮返回到上次访问的网页时,我的 Controller 操作方法没有被执行。
当我们按下后退按钮时,浏览器从缓存中获取数据。所以,如果我们要执行 Controller Action 方法,我们需要防止浏览器缓存该页面。
我用谷歌搜索了很多关于这个。通过这个,我找到了很多基于ASP.NET MVC中缓存的解决方案。比如,禁用缓存。
我检查了这个网站并尝试过。 https://docs.microsoft.com/en-us/aspnet/core/performance/caching/response?view=aspnetcore-2.2
.它不起作用。
我们正在根据 cookie 执行一些操作。所以禁用缓存,也不应该清除这一点。
按浏览器后退按钮时,ASP.NET Core 中还有其他方法可以执行 Controller 操作方法吗?
提前致谢。
最佳答案
使用 no-cache 时应该小心。对于 Caching
,它在性能中起着重要作用。
如果你想用 no-cache
设置特定的 Controller Action ,你可以遵循:
CacheProfiles
在 Startup.cs
services.AddMvc(options =>
{
options.CacheProfiles.Add("Never",
new CacheProfile()
{
Location = ResponseCacheLocation.None,
NoStore = true
});
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
[ResponseCache(CacheProfileName = "Never")]
public IActionResult Index()
{
return View();
}
如果您坚持不为所有请求缓存,请尝试中间件。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Use(async (context, next) =>
{
context.Response.OnStarting(() =>
{
if (context.Response.Headers.ContainsKey("Cache-Control"))
{
context.Response.Headers["Cache-Control"] = "no-cache,no-store";
}
else
{
context.Response.Headers.Add("Cache-Control", "no-cache,no-store");
}
if (context.Response.Headers.ContainsKey("Pragma"))
{
context.Response.Headers["Pragma"] = "no-cache";
}
else
{
context.Response.Headers.Add("Pragma", "no-cache");
}
return Task.FromResult(0);
});
await next.Invoke();
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
关于caching - 浏览器后退按钮不执行 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53867945/