Это не так много работы, чтобы заставить его работать в глобальном масштабе. Мы в прошлом создали класс, который происходит из ActionFilter, а затем добавим его как глобальный фильтр действий в global.asax. Также обратите внимание, что фактически принудительное перезагрузка всех браузеров не является тривиальной. Даже приведенный ниже код не всегда работает с Safari, который часто приходится обманывать пустым загрузочным тегом тела или аналогичным.
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