views:

134

answers:

2

Hello, I've implemented url routing under asp.net 3.5 with the following code:

public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            string virtualPath = requestContext.RouteData.Values["page"].ToString();

            //if virtualpath doesn't end in aspx, then it's just a directory path loading
            //default.aspx by default.
            if (!virtualPath.EndsWith(".aspx") && !virtualPath.EndsWith(".txt"))
            {
                virtualPath += "default.aspx";
            }

            return BuildManager.CreateInstanceFromVirtualPath(
                    virtualPath, 
                    typeof(Page)) as Page;
        }

So I can have urls like www.mysite.com/en/products/, where /en/ is not a physical directory, and default.aspx resides under products/ directory and is loaded automatically.

It works for everything except for the root: www.mysite.com/en/. This url fails. There is a default.aspx that exists under www.mysite.com and indeed it works for www.mysite.com/en/default.aspx. However I get an error when going www.mysite.com/en and it's not 404. It's when doing the actual routing. it fails on the first line in the code when it tries to retrieve the "page" attribute from routedata values. It just crashes from object reference not found. I had read somewhere that this was an asp.net problem with the root directory. Do you have any idea about this?

A: 

I fixed it by adding another rule!

here's the better code:

    try
    {
        string virtualPath = requestContext.RouteData.Values["page"].ToString();


        //if virtualpath doesn't end in aspx, then it's just a directory path loading
        //default.aspx by default.
        if (!virtualPath.EndsWith(".aspx") && !virtualPath.EndsWith(".txt"))
        {
            virtualPath += "default.aspx";
        }

        return BuildManager.CreateInstanceFromVirtualPath(
                virtualPath,
                typeof(Page)) as Page;
    }
    catch
    {
        //the following is in case when it's off the root /en/
        return BuildManager.CreateInstanceFromVirtualPath("~/default.aspx", typeof(Page)) as Page;
    }