Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How best to work with the Expires header in ASP.NET MVC?

I want to be able to set a long expires time for certain items that a user downloads via GET request.

I want to say 'this is good for 10 minutes' (i.e. I want to set an Expires header for +10 minutes). The requests are fragments of HTML that are being displayed in the page via AJAX and they're good for the user's session. I don't want to go back to the server and get a 304 if they need them again - I want the browser cache to instantly give me the same item.

I found an article which is almost a year old about MVC Action filter caching and compression. This creates a custom ActionFilter to change the expires header. I'm already using the compression filter which works great for some custom css I am generating (94% compression rate!).

I have two main concerns :

1) Do I really have to use this method. I'm fine with it if I do, but is there really no functionality in MVC or the OutputCache functionality to do this for me? In 'traditional' ASP.NET I've always just set the Expires header manually, but we cant do that anymore - at least not in the controller.

2) If I do use this filter method - is it going to interfere with the OutputCache policy at all - which I want to be able to control in web.config. I'm kind of thinking the two are mutually exclusive and you wouldn't want both - but I'm not completely sure.

like image 237
Simon_Weaver Avatar asked Feb 16 '09 09:02

Simon_Weaver


2 Answers

  1. No, you don't have to use this method. However, I think it is probably the best method to choose, because it makes the controller more testable and less web-aware. The alternative would be to set the header manually in the Controller, like this:

    Response.AddHeader("Expires", "Thu, 01 Dec 1994 16:00:00 GMT");

  2. Well, the OutputCache attribute controls when the action runs at all, and when it returns cached HTML instead. Expires tells the browser when to re-fetch the HTML. So I wouldn't call them mutually exclusive, but they are certainly two sides of the same coin, and you're right to think that you may not need both. I would suggest reviewing the HTTP spec to decide what is most appropriate for your application.

like image 71
Craig Stuntz Avatar answered Sep 18 '22 15:09

Craig Stuntz


Response.Expires This property specifies the number of minutes before a page cached in the browser expires ie. if the user returns to the same page before the specified number of minutes the cached version of the page is displayed.

Response.ExpiresAbsolute Using this property we can set the date and/or time at which page cached in the browser expires.

http://forums.asp.net/t/1532229.aspx

like image 24
vtortola Avatar answered Sep 17 '22 15:09

vtortola