How to 301 redirect in ASP.NET 4.0?

Learning picture Learning · May 20, 2012 · Viewed 29.7k times · Source

I am trying to implement URL redirect for the website rather than doing it page by page. I want to do it in the global.asax file. Below is the code i have defined.

I want to have http://website.net as my main url & want to have a permanent URL redirect if someone types in http://www.website.net.

Unfortunately it is not working for the live website. Can anyone point out the problem in the code. The code doesn't generate any error.

void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup

    if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://website.net"))
    {
        HttpContext.Current.Response.Status = "301 Moved Permanently";
        HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace("http://website.net", "http://www.website.net"));
    }

}

Answer

MartinHN picture MartinHN · May 20, 2012

Main problem: Your're doing the above stuff in Application_Start - which is only executed once. You should hook up with each request. Try this:

void Application_BeginRequest(object sender, EventArgs e) 
{
    // Code that runs on every request

    if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://website.net"))
    {
        HttpContext.Current.Response.Status = "301 Moved Permanently";
        HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace("http://website.net", "http://www.website.net"));
    }

}

An even better approach would be to use URL rewriting, which can be configured from within Web.Config:

Microsoft rewriting module - Force www on url Or remove www from url