Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make ASP.NET MVC Route Id parameter required

I have this route:

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

This routes this fine: mysite.com/place/details/123

Making Id 123 available to the details action of the place controller - which can then lookup place '123'.

However - this URL is also passed to the controller: mysite.com/place/details/

I want this to return HttpNotFound - but it sends a null Id to the controller - and requires me to handle that.

It seems neater if the route itself achieves this rather than needing unseemly null checks in the controller itself.

I have found nothing in Google about this specific issue.

How can I do this?

like image 566
niico Avatar asked Jul 02 '16 15:07

niico


People also ask

How do you add a constraint to a route?

Creating Route Constraint to a Set of Specific Values MapRoute( "Default", // Route name "{controller}/{action}/{id}", // Route Pattern new { controller = "Home", action = "Index", id = UrlParameter. Optional }, // Default values for parameters new { controller = "^H.

What is the default setting for route config in MVC?

Routing in ASP.NET MVC By default route is: Home controller - Index Method. routes. MapRoute has attributes like name, url and defaults like controller name, action and id (optional). Now let us create one MVC Application and open RouteConfig.


2 Answers

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.

like image 104
NightOwl888 Avatar answered Nov 08 '22 21:11

NightOwl888


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

like image 23
Nkosi Avatar answered Nov 08 '22 23:11

Nkosi