如何关闭缓存MVC请求,但不是在IIS7的静态文件? [英] How to switch off caching for MVC requests but not for static files in IIS7?

查看:173
本文介绍了如何关闭缓存MVC请求,但不是在IIS7的静态文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个ASP.NET MVC应用程序。大部分的控制器操作的不应该被高速缓存。因为在这个I输出无缓存标头的的Application_BeginRequest

I'm developing an ASP.NET MVC application. Most of the controller actions are not supposed to be cached. Because of this I output no-cache headers in 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();
    }

该应用程序在运行IIS7的模块配置设置 runAllManagedModulesForAllRequests =真正的。这意味着所有的静态文件通过请求管道,以及(并获得禁用高速缓存)。

The application is running on IIS7 with modules config setting runAllManagedModulesForAllRequests="true". This means that all static files pass through the request pipeline as well (and get caching disabled).

什么是让这些静态文件启用高速缓存的最佳方式?我必须用的Application_BeginRequest 设置响应缓存头前检查分机或者是有一个更简单的方法(如完全绕过静态文件的请求管道)?

What is the best way to keep caching enabled for these static files? Do I have to check on extension before setting the response cache headers in Application_BeginRequest or is there an easier way (like bypassing the request pipeline for static files altogether)?

推荐答案

假设你不能避免使用 runAllManagedModulesForAllRequests =真正的在Hector的链接,你可以检查请求处理程序的类型,只设置缓存头请求是否被MVC处理。

Assuming that you can't avoid using runAllManagedModulesForAllRequests="true" as in Hector's link, you could check the type of the request handler and only set the caching headers if the request is being handled by 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();
    }
}

请注意,我已经感动了code到 Application_ preRequestHandlerExecute ,因为处理程序尚未在的BeginRequest选择,所以 HttpContext.Current.CurrentHandler 为null。

Note that I've moved the code into Application_PreRequestHandlerExecute because the handler hasn't yet been chosen in BeginRequest, so HttpContext.Current.CurrentHandler is null.

这篇关于如何关闭缓存MVC请求,但不是在IIS7的静态文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆