Sponsored

Friday, May 30, 2008

Last-Modified HTTP header on ASP.NET page

"Last-Modified" HTTP header is an important part of every web page since it helps browsers to cache pages' content locally and thus save HTML traffic. It is also used by internet search engines in order to determine the relevance of the pages' content and thus improves pages' indexing.

By default, a standard ASP.NET page does not include a "Last-Modified" header in the output HTML. One of the possible explanation for such behavior is that an ASPX page is considered dynamic by nature meaning that its content might be updated every time the page is requested. It is true in many cases for data-driven and interactive pages but most of the dynamic web sites also contain pages that are updated relatively rare or static.

So, when does it make sense to add a "Last-Modified" header to the page? First candidates usually are data-driven pages that display information from some sort of content storage systems (databases, files, etc.) and that information changes but not very frequently so there is a possibility that the same content may be viewed many times. Other apparent candidates are static pages even if they are data-driven but their content does not change for the lifetime.

What are the pages that do not need the "Last-Modified" header? Obvious candidates are interactive pages and pages that displays user session related data.

ASP.NET provides two methods to set the "Last-Modified" header on the page. Both of them belong to the HttpCachePolicy class and are accessible through the Cache property of the Response object:


	Response.Cache.SetLastModified(DateTime date);
	Response.Cache.SetLastModifiedFromFileDependencies();
The first method takes a DateTime parameter that allows you to apply some algorithm for calculating the Last-Modified date of the page, for instance based on information from a database. The second method will calculate the date stamp automatically based for instance on the assembly build date. For the second method you can also include additional file dependencies in date calculation using

	Response.AddFileDependancy(string filename);
For instance if a page displays a content of a static XML file you could include that XML file in the dependency and the "Last-Modified" header's value would be updated based on that file's "Date Modified" attribute.

No comments:

Post a Comment