如何从asp.Net mvc应用程序中禁用自动浏览器缓存?
因为我有一个缓存的问题,因为它缓存所有的链接。但有时它会自动重定向到默认的索引页面,它存储了缓存,然后我一直点击那个链接,它会将我重定向到默认的索引页面。
所以有人知道如何在ASP.NET MVC4中手动禁用缓存选项?
发布于 2012-10-18 14:22:41
您可以使用OutputCacheAttribute
来控制特定操作或控制器中所有操作的服务器和/或浏览器缓存。
禁用控制器中的所有操作
[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)] // will be applied to all actions in MyController, unless those actions override with their own decoration
public class MyController : Controller
{
// ...
}
对特定操作禁用:
public class MyController : Controller
{
[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)] // will disable caching for Index only
public ActionResult Index()
{
return View();
}
}
如果要将默认缓存策略应用于所有控制器中的所有操作,可以通过编辑global action filter并查找RegisterGlobalFilters
方法来添加global.asax.cs
。此方法被添加到默认的MVC应用程序项目模板中。
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new OutputCacheAttribute
{
VaryByParam = "*",
Duration = 0,
NoStore = true,
});
// the rest of your global filters here
}
这将导致它将上面指定的OutputCacheAttribute
应用于每个操作,这将禁用服务器和浏览器缓存。您应该仍然能够通过将OutputCacheAttribute
添加到特定的操作和控制器来覆盖此无缓存。
发布于 2012-10-19 05:35:46
HackedByChinese没有抓住要点。他把服务器缓存和客户端缓存弄错了。OutputCacheAttribute控制服务器缓存(IIS http.sys缓存),而不是浏览器(客户端)缓存。
我给你我的代码库的一小部分。明智地使用它。
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public sealed class NoCacheAttribute : FilterAttribute, IResultFilter
{
public void OnResultExecuting(ResultExecutingContext filterContext)
{
}
public void OnResultExecuted(ResultExecutedContext filterContext)
{
var cache = filterContext.HttpContext.Response.Cache;
cache.SetCacheability(HttpCacheability.NoCache);
cache.SetRevalidation(HttpCacheRevalidation.ProxyCaches);
cache.SetExpires(DateTime.Now.AddYears(-5));
cache.AppendCacheExtension("private");
cache.AppendCacheExtension("no-cache=Set-Cookie");
cache.SetProxyMaxAge(TimeSpan.Zero);
}
}
用法:
/// will be applied to all actions in MyController
[NoCache]
public class MyController : Controller
{
// ...
}
明智地使用它,因为它确实禁用了所有客户端缓存。唯一未禁用的缓存是“后退按钮”浏览器缓存。但似乎真的没有办法绕过它。也许只能通过使用javascript来检测它,并强制页面或页面区域刷新。
发布于 2014-09-02 19:20:34
我们可以在Web.config文件中设置缓存配置文件,而不是在页面中单独设置缓存值,以避免冗余代码。我们可以通过使用OutputCache属性的CacheProfile属性来引用概要文件。此缓存配置文件将应用于所有页面,除非页面/方法覆盖这些设置。
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="CacheProfile" duration="60" varyByParam="*" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
如果您想从您的特定操作或控制器禁用缓存,您可以通过如下所示的修饰该特定操作方法来覆盖配置缓存设置:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult NoCachingRequired()
{
return PartialView("abcd");
}
希望这篇文章很清楚,并对你有用。
https://stackoverflow.com/questions/12948156
复制相似问题