讓它在全球範圍內工作並不是太多工作。我過去所做的是創建一個派生自ActionFilter的類,然後將其作爲global.asax中的全局動作過濾器添加。另請注意,實際上強制所有瀏覽器重新加載並非微不足道。即使下面的代碼並不總是與Safari一起使用,Safari通常不得不通過空身體標籤或類似的onload來欺騙。
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;
/// <summary>
/// Action filter that instructs the page to expire.
/// </summary>
public class PageExpirationAttribute : ActionFilterAttribute
{
/// <summary>
/// The OnActionExecuted method.
/// </summary>
/// <param name="filterContext">The current ActionExecutedContext. </param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
filterContext.HttpContext.Response.ClearHeaders();
filterContext.HttpContext.Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate, post-check=0, pre-check=0, max-age=0");
filterContext.HttpContext.Response.AppendHeader("Pragma", "no-cache");
filterContext.HttpContext.Response.AppendHeader("Keep-Alive", "timeout=3, max=993");
filterContext.HttpContext.Response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
}
}
如果您希望能夠排除某些頁面,則可以創建可應用於控制器或方法的另一個屬性。你OnActionExecuting()可以檢查是否存在該屬性:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class AllowCachingAttribute : Attribute
{
}
近似代碼添加到OnActionExecuting
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;
/// <summary>
/// Action filter that instructs the page to expire.
/// </summary>
public class PageExpirationAttribute : ActionFilterAttribute
{
/// <summary>
/// The OnActionExecuted method.
/// </summary>
/// <param name="filterContext">The current ActionExecutedContext. </param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
bool skipCache = filterContext.ActionDescriptor.IsDefined(typeof(AllowCachingAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowCachingAttributee), true);
if (!skipCache)
{
filterContext.HttpContext.Response.ClearHeaders();
filterContext.HttpContext.Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate, post-check=0, pre-check=0, max-age=0");
filterContext.HttpContext.Response.AppendHeader("Pragma", "no-cache");
filterContext.HttpContext.Response.AppendHeader("Keep-Alive", "timeout=3, max=993");
filterContext.HttpContext.Response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
}
}
}
他當然可以。他爲什麼不應該?但是,他不能執行任何操作。更改緩存設置僅影響當前頁面。 – jgauffin