如何将站点范围的无缓存标头添加到MVC 3应用程序
我构建了一个MVC3应用程序,应用程序有很多页面,现在因为我需要在http标头中添加无缓存设置的安全问题,是否有更简单的方法呢? 如果我们可以修改一个地方,那么它将适用于整个应用程序,它将是完美的。
你们能帮助我吗?
如何在Global.asax中的Application_PreSendRequestHeaders
事件中设置Headers ?
编辑您可以使用Response.Cache.SetCacheability
而不是直接设置标题。*
void Application_PreSendRequestHeaders(Object sender, EventArgs e) { Response.Cache.SetCacheability(HttpCacheability.NoCache); }
在Fiddler测试。
通过手动设置标题的替代方法。
void Application_PreSendRequestHeaders(Object sender, EventArgs e) { Response.Headers.Set("Cache-Control", "no-cache"); }
替代那些想要方法/动作或类/控制器广泛的no-cache
[OutputCache(Location = OutputCacheLocation.None)] public class HomeController : Controller { ... }
如下所述:
OutputCacheLocation枚举
无:已为请求的页面禁用输出缓存。 此值对应于HttpCacheability.NoCache枚举值。
HttpCacheability枚举
NoCache – 设置Cache-Control:no-cache标头….
设置全局filter。
public class MvcApplication : System.Web.HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new NoCacheGlobalActionFilter()); } } public class NoCacheGlobalActionFilter : ActionFilterAttribute { public override void OnResultExecuted(ResultExecutedContext filterContext) { HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache; cache.SetCacheability(HttpCacheability.NoCache); base.OnResultExecuted(filterContext); } }
我会在IIS本身(假设您正在使用它)或web.config中执行此操作:
更少的代码是更好的代码。
根据IIS的版本,设置略有不同。
有关详细信息,请参见此处
我建议这些调用仅限于非GET请求,以避免在GET上失去缓存的好处。 以下内容确保即使是像iOS 6 Safari这样的积极缓存浏览器也不会缓存任何非GET请求的内容。
我使用所有控制器inheritance的Controller基类有很多原因,这很好用,因为我的Initialize重写可以有条件地设置我的缓存头。
public class SmartController : Controller { ... public HttpContextBase Context { get; set; } protected override void Initialize(System.Web.Routing.RequestContext requestContext) { Context = requestContext.HttpContext; if (Context.Request.RequestType != "GET") { Context.Response.Cache.SetCacheability(HttpCacheability.NoCache); } base.Initialize(requestContext); ... } ... }