【问题标题】:Dynamic Routing in asp.net webformsasp.net webforms中的动态路由
【发布时间】:2014-04-14 09:43:30
【问题描述】:

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

例如,假设我有多个路线用于同一页面

虽然我的页面实际 URL 类似于 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");
        }

非常感谢您提供指向一个好的示例或解决方案的指针。

【问题讨论】:

  • HTTP Handlers 也可以做到这一点,而不是将您的代码放在global.asax 中。
  • @juan.facorro,你能指点我其他的例子吗

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


【解决方案1】:

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

不过,对于动态页面/URL,如果请求与任何静态路由都不匹配,我倾向于使用 catch all 路由来处理请求。

例如

    // 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" } }
    );

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

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

【讨论】:

    【解决方案2】:

    ASP.NET Routing 能帮到你吗?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-08
      • 2016-01-06
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 2012-03-19
      相关资源
      最近更新 更多