代码之家  ›  专栏  ›  技术社区  ›  Mr. Flibble

ASP.NET MVC路由-如何匹配整个URL?

  •  5
  • Mr. Flibble  · 技术社区  · 15 年前

    我正在尝试创建一个catch all路由来跟踪分支字符串在URL中的时间。仿射代码由 x 其次是 int ,并且只显示在URL的末尾(但在查询字符串之前)。

    我的想法是提取关联ID,进行一些日志记录,然后在没有关联ID的情况下对同一请求执行301。

    例如:

    http://www.domain.com/x32
    http://www.domain.com/x32/
    http://www.domain.com/path/to/something/x32
    http://www.domain.com/x32?query=string
    http://www.domain.com/x32/?query=string
    http://www.domain.com/path/to/something/x32?query=string
    http://www.domain.com/path/to/something/x32/?query=string
    

    我有这条路

    routes.Add(new Route("{url}/x{affiliateExternalId}", new MvcRouteHandler())
    {
         Defaults = new RouteValueDictionary(
          new { controller = "Home", action = "LogCookieAndRedirect" }
         ),
         Constraints = new RouteValueDictionary(new { affiliateExternalId = @"\d{1,6}" })
    });
    

    哪一个匹配

    http://www.domain.com/path/x32
    http://www.domain.com/path/x32/
    

    我需要做什么来匹配所有内容并将查询字符串传递给控制器?有一个 * 我怀疑我应该用的接线员,但我不能让它做我需要的。

    3 回复  |  直到 15 年前
        1
  •  10
  •   stevemegson    15 年前

    {*url} 将匹配整个路径,而不是只匹配一个段。但是,由于它与整个路径匹配,因此您无法在末尾匹配关联ID。路线将匹配每个请求。你可以通过添加一个路由约束来解决这个问题。 url 在结尾处具有关联ID:

    routes.MapRoute(
        "WithAffiliate",
        "{*url}",
        new { controller="Home", action="LogCookieAndRedirect" },
        new { url = @"/x[0-9]+$" }
     );
    

    然后,您的操作将需要从 网址 参数本身。如果您有修改URL结构的选项,那么如果ID位于路径的开头,则可以匹配它:

    routes.MapRoute(
        "WithAffiliate",
        "x{affiliateExternalId}/{*url}",
        new { controller="Home", action="LogCookieAndRedirect" }
     );
    
        2
  •  0
  •   Robert Harvey    15 年前

    如果我这样做,我会使它成为查询字符串中的一个值。

    例子:

    http//www.domain.com/path/to/something?affiliate=X32&query=string
    

    问题是关联ID是 可选择的 .如果您将其放入路径中,您将根据分支ID是否存在来更改路径的结构,因此您必须对每个路由执行两次(一次使用分支ID,一次不使用分支ID)。

        3
  •  0
  •   Community Nick Dandoulakis    7 年前

    如果只定义了一个路由,则只能使用此“捕获所有路由”。但是如果你有多条路线,你就得加上 {affiliateExternalId} 所有路径的参数(除非我丢失了什么)。

    我第二 Robert Harvey suggestion .