301 Moved Permanently Redirect in ASP.NET

If you have done SEO work, you know that Search Engines would penalize my site if both http://www.mysite.com and http://mysite.com/ requests returned a 200 OK code in the HTTP header. Why? Because from a Search Engine's spider point of view, there are 2 sites, one with the www prefix, and one without it, yet in reality they the same site.
The solution for this is to do a 301 Redirect.

You can do this:

protected void Page_Load(object sender, EventArgs e)
{
   Response.Status = "301 Moved Permanently" ;
   Response.AddHeader( "Location" ,"http://www.mysite.com" );
}

But this code needs to be applied on every webpage.

 So a general solution to overcome this problem is writting the code in global.asax file's Application_BeginRequest event and the code will looks like:

void Application_BeginRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://mysite.com"))
        {
            HttpContext.Current.Response.Status = "301 Moved Permanently";
            HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace("http://mysite.com", "http://www.mysite.com"));
        }
    }

So now if you type http://mysite.com you will get 301 Moved Permanently instead of 200 OK and site will automatically redirect to http://www.mysite.com. The new result means the Search Engines will consider both urls to point to the same site, so all page rankings will add up regardless of the entry point.

301 redirection