I built a MVC3 app, the applicaiton have lot of pages, now because security issues I need to add the no-cache setup in http headers, Is any easier way to do it? if we can modify one place then it will working for entire application, it will be perfect.
Can you guys help me out?
How about setting the Headers inside the Application_PreSendRequestHeaders
event in Global.asax?
EDIT
You can use Response.Cache.SetCacheability
rather than setting the Headers directly.*
void Application_PreSendRequestHeaders(Object sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
Tested in Fiddler.
Alternative way by setting the Headers manually.
void Application_PreSendRequestHeaders(Object sender, EventArgs e) {
Response.Headers.Set("Cache-Control", "no-cache");
}
Alternative for those wanting method/action or class/controller wide no-cache
[OutputCache(Location = OutputCacheLocation.None)]
public class HomeController : Controller
{
...
}
As explained here:
OutputCacheLocation Enumeration
None : The output cache is disabled for the requested page. This value
corresponds to the HttpCacheability.NoCache enumeration value.
HttpCacheability Enumeration
NoCache - Sets the Cache-Control: no-cache header....
Set up a global 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);
}
}
http://dotnet.dzone.com/articles/output-caching-aspnet-mvc
I would do it in IIS itself (assuming you are using that), or the web.config:
<configuration>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</configuration>
Less code is better code.
The setup is slightly different based on the version of IIS.
See here for more info.
I recommend that these calls be limited to non-GET requests, to avoid losing the benefit of cache on GETs. The following ensures that even aggressive caching browsers like iOS 6 Safari will not cache anything that is not a GET request.
I use a Controller base class that all of my controllers inherit from for a number of reasons, and this served well in that my Initialize override can handle setting my caching headers conditionally.
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);
...
}
...
}