且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使ASP.NET MVC路由ID参数为必需

更新时间:2023-02-16 18:10:50

要使id值为必需,则不能将其设置为UrlParameter.Optional或提供任何其他默认值.该网址段中没有值,也没有默认值,该路由将与请求不匹配.

To make the id value required, you must not set it as UrlParameter.Optional or provide any other default value. With no value in the URL segment, and no default, the route won't match the request.

routes.MapRoute(
    "PlaceDetails",
    "{controller}/{action}/{id}",
    new { controller = "Place", action = "Details" }
);

但是您可能还需要以另一种方式限制该路由,以防止在不该匹配的情况下匹配该路由.

But you probably also need to constrain the route in another way to prevent it from matching in cases where it shouldn't.

routes.MapRoute(
    "PlaceDetails",
    "Place/{action}/{id}",
    new { controller = "Place", action = "Details" }
);

有关详细信息和其他选项,请参见为什么在asp.net mvc中先将特殊路由映射到普通路由之前?.

See Why map special routes first before common routes in asp.net mvc? for details and additional options.