url路由不适用于根文件夹

时间:2009-09-03 16:22:22

标签: asp.net-3.5 url-routing

我已经使用以下代码在asp.net 3.5下实现了url路由:

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;
        }

所以我可以使用www.mysite.com/en/products/这样的网址,其中/ en /不是物理目录, default.aspx位于products /目录下,并自动加载。

它适用于除root之外的所有内容:www.mysite.com/en/。这个网址失败了。在www.mysite.com下有一个default.aspx,实际上它适用于www.mysite.com/en/default.aspx。但是当我访问www.mysite.com/en时出现错误并且它不是404.这是在进行实际路由时。当它尝试从routedata值中检索“page”属性时,它在代码的第一行失败。它只是从未找到的对象引用崩溃。我曾在某处读到这是根目录的asp.net问题。你对此有什么想法吗?

2 个答案:

答案 0 :(得分:0)

我通过添加其他规则修复了它!

这是更好的代码:

    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;
    }

答案 1 :(得分:0)