それをグローバルに機能させるのは大したことではありません。過去に、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");
}
}
}