1

如何{controller}/{id}在 ASP.NET MVC 5 中设置路由。我想实现的目标:如果没有{action}定义,请Index()使用id.

我试过thism但没有用:

// 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 }
);
4

1 回答 1

0

在阅读了ameer的评论之后,很明显路由并不是我希望的那样“智能”,所以如果 URL 模式匹配一​​个路由,但没有找到这样的控制器/方法,它不会“落入”下一个路由命令,但会引发异常。

所以我尝试了西蒙的建议,为我的自定义路由添加了约束,并颠倒了顺序,现在它可以工作了。但是,如果我想有其他类似附件的映射,我就必须一一添加。

工作代码:

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 }
);
于 2013-09-02T20:30:12.453 回答