高级 ASP 路由教程和示例
我最近遇到的主要障碍之一是了解我一直在开发的一些基于 MVC 的应用程序的一些更复杂的路由要求。 我无法找到合适的教程来引导我完成它以获得完整的理解。
我想找到一套完整的教程,涵盖从基本(控制器/操作/id)到高级的所有路由。
我所说的高级路由的一个示例如下:
/blog/year/month/day/title
- 将映射到控制器:blog
和操作:post
和参数:year
、month
、day
和 title
/blog /title
- 将映射到控制器:blog
和操作:post
以及参数:title
/title - 将映射到控制器:
blog
和操作:post
并作为参数:title
我可以将每个可能的集合映射到显式路由全局使用数据库,但这似乎违背了让路由引擎路由到正确位置的目的。我宁愿定义一次规则。
One of major hurdles I seem to be having recently is getting my head around some of the more complex routing requirements for some MVC based applications I've been developing.
I'm having problems finding the right set of tutorials to walk me through it to get a complete understanding.
What I'd like to find is a complete set of tutorials for everything routing from basic (controller/action/id) to advanced.
An example of what I'm calling advanced routing is things like:
/blog/year/month/day/title
- would map to controller: blog
and action: post
and as parameters: year
, month
, day
and title
/blog/title
- would map to controller: blog
and action: post
and as parameters: title
/title
- would map to controller: blog
and action: post
and as parameters: title
I could map each possible set to an explicit route in global using a database, but that seems like it's defeating the point of having the routing engine route to the correct place. I'd rather define the rule once.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不明白,为什么不能将它们中的每一个定义为单独的路由,并在需要时使用正则表达式。例如,区分
/blog/year/month/day/title
和/blog/title
。这些集合中的每一组都是一个单独的案例,您需要告诉 MVC 如何处理每一组。您可以通过在
Global.asax.cs
文件中定义一次规则
来完成此操作:对于第一种情况:
/blog/year/month/day/title
对于第二种情况:
/blog/title
对于最后一种情况:
/title
技巧是将这些路由按照这个确切的顺序放置,最不具体的放在底部。更改顺序会导致使用错误的路线(特别是最后两条)。如果最后一种情况与第二种情况切换,
blog/SomeTitle
类型的 URL 将路由到以blog
作为标题的post
操作。每当您为某些内容创建路由时,请记住以下几点:
非常
注意路由顺序(哪个路由在哪个路由之前){something}
表示操作参数一些很好的教程:
I don't understand, why can't you just define each one of them as a separate route, using regular expression when needed. For example to differentiate between the
/blog/year/month/day/title
and/blog/title
.Each one of those sets is a separate case, and you'll need to tell MVC what to do with each one. You can do this by
defining the rule once
in theGlobal.asax.cs
file:For the first case:
/blog/year/month/day/title
For second case:
/blog/title
For last case:
/title
The trick is putting theses routes in this exact order, with the least specific at the bottom. Changing the order would result in the wrong route being used (specifically in the last two). If the last case was switched with the second case, URLS of the type
blog/SomeTitle
would route to thepost
action withblog
as the title.Whenever you're creating a route for something, keep the following in mind:
very
aware of route order (which route comes before which){something}
denote action parametersSome good tutorials: