c# - MVC4 : same url base for different actions

标签 c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing

我想有 2 条类似于这些的路线:

routes.MapRoute("Detail", "guide/{urlname}", new { controller = "Application", action = "Detail" });
routes.MapRoute("Search", "guide/{keyword1}/{keyword2}", new { controller = "Guide", action = "Index", keyword1 = UrlParameter.Optional, keyword2 = UrlParameter.Optional });

所以一个路由是根据对象的url名称在数据库中查找对象的详情页面,另一个路由是根据应用生成的关键字搜索结果页面,两者共享同一个url根(/指南)。这两个 Action 在不同的 Controller 中。可能的网址是:

/guide/evernote        --> should route to the application detail page
/guide                 --> should route to search results without filter
/guide/iphone          --> should route to iphone apps search results
/guide/iphone/medical  --> should route to medical iphone apps search results

显然,像这样,第二个路由永远不会匹配到像 /guide/iphone 这样的 url,因为第一个路由已经匹配了相同的 url。

如果 Controller 在数据库中找不到对象,我不想在第一个操作中进行重定向。那么还有哪些其他选择呢?我需要为此创建自定义 RouteHandlerUrlRoutingModule 还是有更简单的方法?

最佳答案

如果 {urlname} 是一个 url,你可以添加一个约束来测试 url 是否匹配正则表达式:

http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-a-route-constraint-cs

关于c# - MVC4 : same url base for different actions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14340198/

相关文章:

c# - 如何调用以字符串为分隔符的String.Split?

c# - 我可以绑定(bind)到实用程序类吗?

c# - HTML 5 - <text> 的作用是什么?

c# - 无法在我的 View 模型中访问对象的属性

asp.net-mvc-4 - RavenDb Mini Profiler 仅在首页加载时加载

c# - 具有私有(private)密封类的 Activator.CreateInstance

c# - 将 .bot 文件中的设置迁移到 appsettings 时如何修复机器人配置

asp.net-mvc - 防伪 token 适用于用户 ""但当前用户是 "user"Google Chrome

c# - 无法运行启用迁移 VS2013 SP4

c# - ASP.Net MVC3/4 多模板