asp.net webforms中的动态路由

时间:2014-04-14 09:43:30

标签: c# asp.net webforms url-routing

我们可以动态添加到global.asax文件

的路由

假设我有同一页面的多条路线,例如

虽然我的网页实际网址类似于http://website.com/en/about-us

我现在的问题是:有没有办法可以在global.asax文件中动态定义这些路由,以便它读取用户输入的URL,如http://website.com/about,然后将其与数据库表进行比较并将其重定向到正确的页面http://website.com/en/about-us

考虑以下表格结构:

Id  URL_Name    URL                                 Actual_URL                              Page_Handler
1   Home        http://website.com/                 http://website.com/                     Default.aspx
2   About Us    http://website.com/about            http://website.com/en/about-us          About.aspx
3   About Us    http://website.com/about-us         http://website.com/en/about-us          About.aspx
4   About Us    http://website.com/en/about         http://website.com/en/about-us          About.aspx
5   Contact     http://website.com/contact          http://website.com/en/contact-us        Contact.aspx
6   Contact     http://website.com/en/contact       http://website.com/en/contact-us        Contact.aspx

现在我必须在global.asax

中手动配置每条路线
        if(HttpContext.Current.Request.Url.ToString().ToLower().Equals("http://website.com/about")
        {
            HttpContext.Current.Response.Status = "301 Moved Permanently";
            HttpContext.Current.Response.Redirect("http://website.com/en/about-us");
        }


        if(HttpContext.Current.Request.Url.ToString().ToLower().Equals("http://website.com/en/about")
        {
            HttpContext.Current.Response.Status = "301 Moved Permanently";
            HttpContext.Current.Response.Redirect("http://website.com/en/about-us");
        }

非常感谢指向优秀示例或解决方案的指针。

2 个答案:

答案 0 :(得分:2)

我发现global.asax中的路由非常适合静态资源,特别是如果你想要一个漂亮的,性感的无扩展名的SEO网站。

对于动态页面/ URL,我倾向于捕获处理请求的所有路由,如果它不匹配任何静态路由。

例如

    // ignore
    routes.Add(new System.Web.Routing.Route("{resource}.axd/{*pathInfo}", new System.Web.Routing.StopRoutingHandler()));

    // sexy static routes
    routes.MapPageRoute("some-page", "some-sexy-url", "~/some/rubbish/path/page.aspx", true);

    // catch all route
    routes.MapPageRoute(
       "All Pages",
       "{*RequestedPage}",
       "~/AssemblerPage.aspx",
       true,
       new System.Web.Routing.RouteValueDictionary { { "RequestedPage", "home" } }
    );

因此,当请求进入时,它依次检查每个静态路由并执行指定的页面。如果未找到匹配项,则会直接访问catch all,然后AssemblerPage.aspx处理请求。这个AssemblerPage将分析请求的URL并重定向,重写路径或在页面上粘贴一些控件来呈现 - 基本上,它可以做你想做的任何事情。

在您的情况下,我让AssemblerPage检查数据库并将请求的URL与表中的URL进行比较。然后只需重定向或重写路径。

答案 1 :(得分:0)

ASP.NET路由会帮助你吗?

看看这个: - ASP.net URL rewrite based off query string ID