c# - 使 ASP.NET MVC 路由 ID 参数成为必需的

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

我有这条路线:

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/

相关文章:

javascript - api 路由工作错误

c# - ASP.net 将数据项放入转发器中

c# - httpWebRequest 下载并解析excel文件?

c# - 在 Nest ElasticSearch 中重复使用计数和搜索查询

c# - 处理谷歌地图的纬度/经度坐标

asp.net - 带有内联样式表和媒体查询的 Razor View

regex - .Net MVC 路由用于不确定数量的文件夹(嵌套类别结构)

c# - 为什么 HttpWebResponse.ContentLength 突然返回 -1?

c# - 从 Active Directory 进行身份验证,但从 MVC 中的 SQL 数据库授权角色

asp.net-mvc - ASP.NET MVC 路由失败,出现 “No type was found that matches the controller named ' Product'。”