我有这条路线:
routes.MapRoute(
"PlaceDetails",
"{controller}/{action}/{id}",
new { controller = "Place", action = "Details", id = UrlParameter.Optional }
);
这条路线很好: mysite.com/place/details/123
使 Id 123 可用于位置 Controller 的详细操作 - 然后可以查找位置“123”。
然而 - 此 URL 也传递给 Controller : mysite.com/place/details/
我希望它返回 HttpNotFound
- 但它向 Controller 发送了一个 null Id - 并且需要我来处理它。
如果路由本身实现了这一点,而不是需要在 Controller 本身中进行不合时宜的 null 检查,这看起来会更整洁。
我在 Google 中没有发现任何关于这个具体问题的信息。
我该怎么做?
最佳答案
要使 id
值成为必需值,您不得将其设置为 UrlParameter.Optional
或提供任何其他默认值。如果 URL 段中没有值,也没有默认值,路由将不会匹配请求。
routes.MapRoute(
"PlaceDetails",
"{controller}/{action}/{id}",
new { controller = "Place", action = "Details" }
);
但您可能还需要以另一种方式约束路由,以防止它在不应该匹配的情况下匹配。
routes.MapRoute(
"PlaceDetails",
"Place/{action}/{id}",
new { controller = "Place", action = "Details" }
);
参见 Why map special routes first before common routes in asp.net mvc?有关详细信息和其他选项。
关于c# - 使 ASP.NET MVC 路由 ID 参数成为必需的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38161772/