LearnFast.Ninja

Redirect from root to www using global asax redirect ASP.NET

For redirect your site so it will be only with www, add Global.asax to your project if not exist already. In the Application Begin Request function write the following code.

Step 1: Add Global.asax to your project if not exist already.
Web Application:

Web Site:


Step 2: Create static class and place there this function that replace http with http://www

public static class WWW_Only

{

    public static void Do()

    {

        if (!HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://localhost"))

        {

            if (!HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://www."))

            {

                HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.ToString().ToLower().Replace("http://""http://www."));

            }

        }

    }

}


Step 3: Add the Application_BeginRequest function to the Global.asax file and call the www function.

protected void Application_BeginRequest(object sender, EventArgs e)

{

    WWW_Only.Do();

}


Result:


Tags

asp.net

global-asax www www-only beginrequest begin-request application