Car*_*lis 6 .net c# iis asp.net-mvc caching
我正在开发一个ASP.NET MVC应用程序.大多数控制器操作都不应该被缓存.因此我输出no-cache标头Application_BeginRequest:
protected void Application_BeginRequest()
{
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
}
Run Code Online (Sandbox Code Playgroud)
应用程序在IIS7上运行,并带有模块配置设置runAllManagedModulesForAllRequests="true".这意味着所有静态文件也会通过请求管道(并禁用缓存).
为这些静态文件启用缓存的最佳方法是什么?在设置响应缓存标头之前是否必须检查扩展?Application_BeginRequest或者是否有更简单的方法(例如完全绕过静态文件的请求管道)?
假设您无法避免runAllManagedModulesForAllRequests="true"在 Hector 的链接中使用 as,则可以检查请求处理程序的类型,并且仅在请求由 MVC 处理时设置缓存标头。
protected void Application_PreRequestHandlerExecute()
{
if ( HttpContext.Current.CurrentHandler is MvcHandler )
{
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我已将代码移至 中Application_PreRequestHandlerExecute,因为尚未在 中选择处理程序BeginRequest,因此HttpContext.Current.CurrentHandler为 null。
| 归档时间: |
|
| 查看次数: |
2512 次 |
| 最近记录: |