Wednesday, March 9, 2011

Here is a simple method of ensure all requests to your application domain include the WWW subdomain prefix.
Place the following code in your Global.asax file.

Note: Uncomment the code in the RedirectToWWW method should you need to prevent redirects while testing locally.

    // global.asax
    protected void Application_BeginRequest(Object sender, EventArgs e)

    private static void RedirectToWWW()
            // prevent adding www. when testing
            // if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("localhost"))
            //  return;

            // Redirect to if the user types in
            if (HttpContext.Current.Request.Url != null 
                && !String.IsNullOrEmpty(HttpContext.Current.Request.Url.Host)                
                && !HttpContext.Current.Request.Url.Host.ToLower().StartsWith("www"))
                HttpContext.Current.Response.Redirect("http://www." + HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.Url.AbsolutePath);