asp.net-mvc - Asp.Net MVC 路由 - 如何匹配整个 URL?

标签 asp.net-mvc routing url-routing asp.net-mvc-routing

我正在尝试创建一个包罗万象的路由来跟踪附属字符串何时在 URL 中。附属代码由 x 标记后跟一个 int , 并且只会出现在 URL 的末尾(但在查询字符串之前)。

这个想法是我将提取成员(member) ID,做一些日志记录,然后对没有成员(member) 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/

我需要做什么来匹配所有内容并将查询字符串传递给 Controller ​​?有一个*我怀疑我应该使用的运算符,但我无法让它做我需要的事情。

最佳答案

{*url}将匹配整个路径,而不仅仅是一段。但是,由于它匹配整个路径,因此您无法匹配最后的成员(member) ID。该路由将匹配每个请求。您可以通过添加路由约束来检查 url 来解决这个问题。最后有一个附属 ID:

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

然后,您的操作将需要解析来自 url 的成员(member) ID。参数本身。如果您可以选择修改 URL 结构,则可以匹配位于路径开头的 ID:
routes.MapRoute(
    "WithAffiliate",
    "x{affiliateExternalId}/{*url}",
    new { controller="Home", action="LogCookieAndRedirect" }
 );

关于asp.net-mvc - Asp.Net MVC 路由 - 如何匹配整个 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1618896/

相关文章:

python - bottle.py URL 路由和反向 howto?

ruby-on-rails - 如何在没有 Rails 4 的情况下向所有 url 添加一个 trailing_slash?

c# - 你在哪里存储验证逻辑?

asp.net-mvc - 用于 mvc 3 的 jquery ui 助手

asp.net-mvc - Ajax.Actionlink 无法与 Telerik MVC Grid 一起使用

node.js - 我可以通过 express next() 函数发送数据吗?

c# - 使用 Bootstrap 从 HTML 转换为 .NET MVC

c# - 查看将从路由执行哪个 Controller 和操作?

routing - SAPUI5:是否可以将类似结构的文件夹映射到 sap.m 主视图中的列表控件?

php - 使用 PHP 以正确的方式路由页面请求