我建立了一个MVC3应用程序,这个应用程序有很多页面。由于安全问题,现在我需要在HTTP头部添加no-cache设置。是否有更容易的方法来做到这一点?如果我们可以修改一个地方,那么它将适用于整个应用程序,那将是完美的。
你们能帮帮我吗?
你们能帮帮我吗?
在 Global.asax 中的 Application_PreSendRequestHeaders
事件中设置 Headers 怎么样?
编辑
你可以使用 Response.Cache.SetCacheability
而不是直接设置 Headers.*
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
{
...
}
如此解释:
None : 对请求的页面禁用输出缓存。 此值对应于 HttpCacheability.NoCache 枚举值。
NoCache - 设置 Cache-Control:no-cache 头....
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文件中完成:
<configuration>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</configuration>
代码越少,越好。
根据IIS的版本,设置略有不同。
更多信息请参见此处。
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);
...
}
...
}
Response.Cache.SetCacheability()
方法而不是手动设置头。在Fiddler中测试并按预期工作。 - Marko