【问题标题】:General routing in ASP.NET WebForms, to change "/cpanel/" to "/marketer/"ASP.NET WebForms 中的常规路由,将“/cpanel/”更改为“/marketer/”
【发布时间】:2011-12-03 08:45:27
【问题描述】:

考虑这种情况,在这种情况下,/cpanel/x 模式中的所有传入链接都应转换(重写)为/marketer/x,其中x 代表 URL 的其余部分。例如:

  1. /cpanel/coupons.aspx/marketer/coupons.aspx
  2. /cpanel/sold.aspx?year=2010&product=camera to /marketer/sold.aspx?year=2010&product=camera`

这似乎是一个通用的 URL 重写,我们使用 HttpContext.Current.RewritePath 和一个 HTTP 模块完成了它。但是,我也想知道这是否可以在 Web 表单中使用 ASP.NET 路由功能来完成?

要求是:

  1. 如何定义路由规则
  2. 如何生成与此路由规则相关的 URL

【问题讨论】:

    标签: asp.net routing url-rewriting


    【解决方案1】:

    ** 评论后编辑 **

    您可以通过网络表单使用路由来做到这一点。要获得可以重写 10,000 个 URL 的所需功能,只需将“cpanel”替换为“marketer”,您需要使用通配符。为此,请在 Global.asax 文件中添加以下命名空间和方法:

    <%@ Import Namespace="System.Web.Routing" %>
    
    void RegisterRoutes(RouteCollection routes)
    {
        routes.Ignore("{resource}.axd/{*pathInfo}");
    
        //--- format ("Name", "Route", "Handler")
        routes.MapPageRoute("cPanel", "marketer/{*RouteCPanel}", "~/cpanel/{*RouteCPanel}");
    }
    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        RegisterRoutes(RouteTable.Routes);
    }
    

    注意 {*RouteCPanel} 是您的通配符,这意味着从 URL 中的那一点到结尾读取所有内容,无论那里有什么。我们设置它的方式是您可以放置​​任何具有“/marketer/....”的 URL,它将被重写为“/cpanel/.....”

    希望这会有所帮助。祝你好运!

    【讨论】:

    • 感谢您的帮助。但是这种方法不支持 DRY(不要重复自己)原则,因为这里没有中心化。想象一下,我有 10,000 个页面需要从 coupon 路由到 marketer。那你怎么办?
    猜你喜欢
    • 1970-01-01
    • 2011-08-08
    • 2016-01-06
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    相关资源
    最近更新 更多