15 August, 2011

Set Expires headers in Asp.net

You want to simplify and improve your HTTP cache headers in your ASP.NET site. Caching with HTTP headers is important to every web site, but there are many complicated rules and conflicts among the headers. Here are lots of notes about HTTP headers and their methods in ASP.NET and the C# language.

Key point:
Use the examples here to improve your HTTP headers. ASP.NET provides many options for HTTP header caching.


First, we know that ASP.NET websites may use ASPX files or ASHX handlers to serve static content like images. Keeping with Yahoo's guidelines, use this ASP.NET C# code to set Expires in the far future.

Page that uses Response.Cache [C#]

using System;
using System.Web.UI;

public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Set this ASPX response to expire in one year.
// ... This is essentially 'never'.
Response.Cache.SetExpires(DateTime.Now.AddYears(1));
}
}

Description. IIS7 will set the Cache-Control header automatically when you specify SetExpires. No other caching logic is necessary for static resource caching on client browsers. However, there are other options available. Please see the section on Cache-Control headers.


Yahoo: static pages



Almost all big websites have certain images that never change, such as logos, shopping cart images, rounded borders and gradients, and navigation bars. Yahoo says to use "the Expires header in the HTTP response to tell the client how long a component can be cached." Please see "Best Practices for Speeding Up Your Web Site" at developer.yahoo.com.

Example Expires HTTP Header:
Expires: Thu, 15 Apr 2010 20:00:00 GMT


Description. Yahoo describes the example:


"This is a far future Expires header, telling the browser that this response won't be stale until April 15, 2010. Note that the time format is very specific and you will need to use a special DateTime format in the C# language to create or test it. Please also see the section on DateTime.

Yahoo: dynamic pages
Yahoo recommends the Cache-Control header for dynamic pages. There are several variants of this you can use. Yahoo's best practices: "For dynamic components: use an appropriate Cache-Control header to help the browser with conditional requests." Using Cache-Control gives you overriding power on the cache setting, allowing you to specify options for proxies and the server.

No comments:

Post a Comment