How to switch off caching for MVC requests but not for static files in IIS7?

前端 未结 2 713
忘了有多久
忘了有多久 2020-12-31 23:32

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_Begi

2条回答
  •  长发绾君心
    2021-01-01 00:10

    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();
        }
    }
    

    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.

提交回复
热议问题