让它在全球范围内工作并不多。我们过去所做的是创建一个派生自 ActionFilter 的类,然后将其作为全局操作过滤器添加到 global.asax 中。另请注意,实际上强制所有浏览器重新加载并非易事。即使是下面的代码也并不总是适用于 Safari,这通常必须通过 body 标签或类似的空加载来欺骗。
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");
}
}
}