如何禁用 ASP.NET 网站的所有的 浏览器缓存 ?
生活随笔
收集整理的這篇文章主要介紹了
如何禁用 ASP.NET 网站的所有的 浏览器缓存 ?
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
咨詢區(qū)
Palani:
我在尋找一個方法禁用某個 ASP.NET MVC 網(wǎng)站的所有瀏覽器緩存,我發(fā)現(xiàn)了如下方法。
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.Cache.SetNoStore();而且我也發(fā)現(xiàn)了可以在 html 上追加一個 meta 標記。
<meta?http-equiv="PRAGMA"?content="NO-CACHE">但這種方式不適合我,因為我的網(wǎng)站中會有一些 ajax 請求,自然就無法攜帶meta了。
請問我如何在全局作用域下實現(xiàn)這么一個禁用瀏覽器緩存的功能?
回答區(qū)
JKG:
可以自定義一個繼承 IActionFilter 的類。
public?class?NoCacheAttribute?:?ActionFilterAttribute {??public?override?void?OnResultExecuting(ResultExecutingContext?filterContext){filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);filterContext.HttpContext.Response.Cache.SetNoStore();base.OnResultExecuting(filterContext);} }然后在你需要禁用的作用域下使用 [NoCache] 標記即可,比如下面的 Controller。
[NoCache] [HandleError] public?class?AccountController?:?Controller {[NoCache][Authorize]public?ActionResult?ChangePassword(){return?View();} }NidhinSPradeep
你可以在 ?Global.asax 下的 Application_BeginRequest 方法中實現(xiàn)此功能。
protected?void?Application_BeginRequest(){Response.Cache.SetCacheability(HttpCacheability.NoCache);Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));Response.Cache.SetNoStore();}JKG:
你可以使用 Asp.NET 自帶的 OutputCache 特性。
[System.Web.Mvc.OutputCache(NoStore?=?true,?Duration?=?0,?VaryByParam?=?"*")]直接使用 OutputCache 特性的話,會讓這些代碼零散在項目各處,更好的做好應該是封裝到一個 Controller 中,然后讓需要的 Controller 繼承此 Controller 即可,比如下面的代碼。
[System.Web.Mvc.OutputCache(NoStore?=?true,?Duration?=?0,?VaryByParam?=?"*")] public?class?NoCacheController??:?Controller { }public?class?HomeController?:?NoCacheController { }點評區(qū)
全局禁用瀏覽器的Cache,這需求有點奇葩哈,不過本篇也學習到了如何全局性的配置,有收獲。
總結(jié)
以上是生活随笔為你收集整理的如何禁用 ASP.NET 网站的所有的 浏览器缓存 ?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设计模式之迭代器
- 下一篇: Hello Blazor:(9)Sour