ASP.NET MVC 2 - UrlParameter.Optional 条目必须位于路由末尾吗?
我正在将网站从 ASP.NET MVC 1 迁移到 ASP.NET MVC 2。目前,该网站支持以下路由:
/{country}/{language}/{controller}/{action}
/{country}/{controller}/{action}
/{language}/{controller}/{action}
/{controller}/{action}
country
和 language
的格式为可通过正则表达式区分并具有适当的约束。在 MVC 1 中,我将其中每一个注册为单独的路线 - 对于大约 20 种组合中的每一种。在 MVC 2 中,我一直试图使用 UrlParameter.Optional
使用一条路由来覆盖所有四种情况,但我似乎无法让它工作 - 如果我定义 < code>country 和 language
都是可选的,那么例如路由 /Home/Index
就无法成功匹配该路由。这就是我想做的:
routes.MapRoute("Default",
"{country}/{language}/{controller}/{action}",
new { country = UrlParameter.Optional, language = UrlParameter.Optional,
controller = "Home", action = "Index" },
new { country = COUNTRY_REGEX, language = LANGUAGE_REGEX });
这是不可能的,因为我的选项位于路线的开头,还是我只是错过了一些东西?我找不到任何文档来告诉我我正在做的事情是不可能的,或者为我指明正确的方向。
I am migrating a site from ASP.NET MVC 1 to ASP.NET MVC 2. At the moment, the site supports the following routes:
/{country}/{language}/{controller}/{action}
/{country}/{controller}/{action}
/{language}/{controller}/{action}
/{controller}/{action}
The formats for country
and language
are distinguishable by Regex and have suitable constraints. In MVC 1, I registered each of these as a separate route - for each of around 20 combinations. In MVC 2, I have been trying to get the same thing working with one route to cover all four cases, using UrlParameter.Optional
, but I can't seem to get it working - if I define country
and language
as both optional, then the route /Home/Index
for example doesn't successfully match the route. This is what I am trying to do:
routes.MapRoute("Default",
"{country}/{language}/{controller}/{action}",
new { country = UrlParameter.Optional, language = UrlParameter.Optional,
controller = "Home", action = "Index" },
new { country = COUNTRY_REGEX, language = LANGUAGE_REGEX });
Is this just impossible because my optionals are at the beginning of the route, or am I just missing something? I can't find any documentation to either tell me what I am doing is impossible or to point me in the right direction.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
唔。有趣的。
这是我能想到的最好的。我猜这是一个坏主意,但这是我能想到的唯一解决方法。我有兴趣听到一些建议/疑虑/投诉。
您可以像这样映射一条近视路线:
然后,在您的定位器控制器中,您可以按照您的意愿重定向到正确的操作:
我是一个会耍小把戏的人。我能说什么?
Hmm. Interesting.
Here's the best I could come up with. I'm guessing that this is a bad idea, but it's the only workaround I could think of. I'd be interested to hear some suggestions/concerns/complaints.
You could map a myopic route like this:
Then, in your Localizer controller, you can redirect to the correct action however you'd like:
I'm a man of cheap tricks. What can I say?