3 回答

TA貢獻2039條經驗 獲得超8個贊
您可以使用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();
}
}
如果要對所有控制器中的所有操作應用默認緩存策略,則可以通過編輯并查找方法來添加全局操作過濾器。在默認的MVC應用程序項目模板中添加了此方法。global.asax.csRegisterGlobalFilters
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new OutputCacheAttribute
{
VaryByParam = "*",
Duration = 0,
NoStore = true,
});
// the rest of your global filters here
}
這將導致它對OutputCacheAttribute所有操作應用上面指定的操作,這將禁用服務器和瀏覽器緩存。您仍然可以通過添加OutputCacheAttribute到特定的操作和控制器來覆蓋此無緩存。

TA貢獻1818條經驗 獲得超8個贊
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來檢測它并強制頁面或頁面區域刷新。

TA貢獻1780條經驗 獲得超5個贊
我們可以在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");
}
希望這很清楚,對您有用。
- 3 回答
- 0 關注
- 974 瀏覽
添加回答
舉報