在丢失的情况下添加路由”;动作“;在url({controller}/{id})中
本文关键字:id url controller 动作 情况下 添加 路由 | 更新日期: 2023-09-27 18:29:46
如何在ASP.NET MVC 5中设置{controller}/{id}
路由。我想实现的是:如果没有定义{action}
,那么用id
调用Index()
。
我试过这个,但没用:
// Keep default routing
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
// Add own routing in case of missing "action"
routes.MapRoute(
name: "Controller/Id",
url: "{controller}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
阅读ameer的评论后,很明显,路由并不像我所希望的那样"智能",所以如果URL模式与一个路由匹配,但没有找到这样的控制器/方法,它不会"失败"到下一个路由命令,而是会引发异常。
因此,我尝试了Simon的建议,为我的自定义路由添加了约束,并颠倒了顺序,现在它起作用了。但是,如果我想要其他类似于附件的映射,我必须逐个添加它们。
工作代码:
routes.MapRoute(
name: "Attachments",
url: "attachments/{id}",
defaults: new { controller = "Attachments", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);