Asp.Net MVC路由-如何匹配整个URL? [英] Asp.Net MVC Routing - how do I match the whole URL?

查看:66
本文介绍了Asp.Net MVC路由-如何匹配整个URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个包罗万象的路由来跟踪URL中的附属字符串何时。关联代码由 x 标记,后跟 int 标记,并且仅显示在URL的末尾(

I'm trying to create a catch-all route to track when an affiliate string is in the URL. An affilite code is marked by an x followed by an int, and will only appear at the end of a URL (but before the query string).

这个想法是,我将提取会员ID,进行一些日志记录,然后对没有会员ID的同一请求执行301。

The idea is that I will extract the affiliate ID, do some logging, then do a 301 to the same request without the affiliate ID.

例如:

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/

我该怎么做才能匹配所有内容并将查询字符串传递给控制器​​?我怀疑应该使用 * 运算符,但是我无法执行它。

What do I need to do to match everything and pass the query string to the controller? There is a * operator that I suspect I should use, but I can't get it to do what I need.

推荐答案

{* url} 将匹配整个路径,而不仅仅是一段。但是,由于它与整个路径匹配,因此您最终无法匹配会员ID。该路线将匹配每个请求。您可以通过添加路由约束来检查 url 在结尾是否具有会员ID来解决此问题:

{*url} will match the whole path rather than just one segment. However, since it matches the whole path, you can't then match the affiliate ID on the end. The route will match every request. You can get around that by adding a route constraint to check that url has an affiliate ID at the end:

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

您的操作将需要从 url解析会员ID 参数本身。如果您可以选择修改网址结构,则可以在路径的开头匹配ID:

Your action will then need to parse the affiliate ID from the url parameter itself. If you have the option to modify the URL structure, it would be possible to match the ID if it were at the start of the path:

routes.MapRoute(
    "WithAffiliate",
    "x{affiliateExternalId}/{*url}",
    new { controller="Home", action="LogCookieAndRedirect" }
 );

这篇关于Asp.Net MVC路由-如何匹配整个URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆