views:

832

answers:

2

I implemented a following code in Global.asax file of my web application.

void Application_BeginRequest()
{

    string rule = ConfigurationManager.AppSettings.Get("WwwRule");

    HttpContext context = HttpContext.Current;
    if (context.Request.HttpMethod != "GET" || context.Request.IsLocal)
    {
        return;
    }

    if (context.Request.PhysicalPath.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase))
    {
        string url = context.Request.Url.ToString();

        if (!url.Contains("://www.") && rule == "add")
        {
            string url = context.Request.Url.ToString().Replace("://", "://www.");
            context.Response.Redirect(url);
        }
    }
}

When I am running above code it works as follows

example.com redirects to www.example.com/default.aspx

www.example.com redirects to www.example.com

http://www.example.com/ redirects to http://www.example.com/

last two conditions works very well. But the first condition did'nt works well because its adding "default.aspx" in the URL which I am not intrested in.

Can anyone please tell me how to make it as below

example.com should redirects to http://www.example.com

Thanks

+2  A: 

Actually, the /default.aspx is added before the request reaches the BeginRequest event. If you want to remove it, you have to actually remove it:

void Application_BeginRequest() {
    string rule = ConfigurationManager.AppSettings.Get("WwwRule");

    HttpContext context = HttpContext.Current;
    if (context.Request.HttpMethod != "GET" || context.Request.IsLocal) {
        return;
    }

    if (context.Request.PhysicalPath.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase)) {
        string url = context.Request.Url.ToString();

        if (!url.Contains("://www.") && rule == "add") {
            url = url.Replace("://", "://www.");
            if (url.EndsWith("/default.aspx", StringComparison.OrdinalIgnoreCase) {
               url = url.Substring(0, url.Length - 13);
            }
            context.Response.Redirect(url);
        }
    }
}
Guffa
+1  A: 

Most likely the Request.Url is appending default.aspx because that's the page actually being served at the time (IIS makes this transparent to you because it's one of the default pages).

When you make your new URL that you're going to redirect, add another .Replace("/default.aspx", "") to the end of it. So...

string url = context.Request.Url.ToString().Replace("://", "://www.").Replace("/default.aspx", "");
routeNpingme
That won't work properly in all situations. Although given a very unlikely situation, but it will change "example.com/default.aspxfolder/file" into "www.example.comfolder/file".
Guffa
@Guffa I agree, but simplicity is the point of my answer so that the asker will grasp what is happening in the most basic way and then can expand it as needed. :)
routeNpingme