Make ASP.NET MVC Route Id parameter required

被刻印的时光 ゝ 提交于 2019-12-05 21:17:28
NightOwl888

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" }
);

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

Nkosi

Remove the optional for the id placeholder in the defaults

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

Now mysite.com/place/details/ will not match the route. Provided you don't have another default route mapped.

If the above causes conflicts with your routing you can modify it like this

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

which couples this mapping directly to PlaceController.Details action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!