Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add site-wide no-cache headers to an MVC 3 app

Tags:

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?

like image 857
Harry Liu Avatar asked Aug 17 '11 04:08

Harry Liu


People also ask

What happens if there is no cache-control header?

Without the cache control header the browser requests the resource every time it loads a new(?) page.

How do I add http cache control header?

If you want to enable Cache-Control for all files, add Header set line outside the filesMatch block. As you can see, we set the Cache-Control header's max-age to 3600 seconds and to public for the listed files.

How do I disable HTTP caching?

Here's how... When you're in Google Chrome, click on View, then select Developer, then Developer Tools. Alternatively, you can right click on a page in Chrome, then click Inspect. Click on the Network tab, then check the box to Disable cache.


2 Answers

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"); } 
like image 144
Marko Avatar answered Oct 09 '22 04:10

Marko


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....

like image 42
KCD Avatar answered Oct 09 '22 06:10

KCD