Use If-Modified-Since header in ASP.NET

by Mads Kristensen 20. May 2006 20:08

If you are building a high traffic website, you are probably concerned about bandwidth. Many hosting centres charge based on the amount of bandwidth you use, and it can be rather expensive for high traffic sites.

This is where the If-Modified-Since header comes to the rescue. By utilizing this request header, you can do what is normally referred to as a Conditional Get. This basically means that the server only has to serve content if the browser hasn’t already cached it and nothing has changed since the last request.

It should also result in faster load times because the browsers internal cache is used. Not all browsers support this header or it is somewhat unclear when they use it. However, RSS aggregators have been using it for years making it ideal for serving RSS feeds.

Dynamic generated images and files will probably also benefit from this. Here is a simple way of utilizing the If-Modified-Since header in ASP.NET and C#.

protected void Page_Load(object sender, EventArgs e)
{
   // Set the date from where the content was last modified
   // It you are serving a file, use the last write time
   DateTime contentModified = System.IO.File.GetLastWriteTime("C:\\image.jpg");

   if (IsClientCached(contentModified))
   {
      Response.StatusCode = 304;
      Response.SuppressContent = true;
   }
   else
   {
      Response.Cache.SetLastModified(contentModified);
      // Then serve your RSS feed or dynamic image
      // or anything else for that matter.
   }
}

private bool IsClientCached(DateTime contentModified)
{
   string header = Request.Headers["If-Modified-Since"];

   if (header != null)
   {
      DateTime isModifiedSince;
      if (DateTime.TryParse(header, out isModifiedSince))
      {
         return isModifiedSince > contentModified;
      }
   }

   return false;
}

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags:

ASP.NET

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008