简体   繁体   中英

Asp.net MVC4 mandatory route parameter

I have a RouteConfig like this

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index"}
        );
    }
}

But when i am trying use " http://example.com/controllername/action/166699406 ". It is getting the error below. What I am trying to achieve is, I want to make the id parameter mandatory. If they dont have an id parameter in the url, it should not hit a route and should show 404. I know we can achieve this by null checking the parameter in the controller. Is there any way manage that in route config itself.

No route in the route table matches the supplied values.

Exception Details: System.InvalidOperationException: No route in the route table matches the supplied values.

You should handle this in web.confing not in routing.

<customErrors mode="On" defaultRedirect="/error/default">
  <error statusCode="403" redirect="/error/restricted"/>
  <error statusCode="404" redirect="/Default/DefaultRoute"/>
  <error statusCode="500" redirect="/error/problem"/>
</customErrors>

If I understand correctly you want to add a constraint to the route

constraints: new { id = @"([0-9]+)" }

this will mean the route will only match when id is a number, it is mandatory.

in full:

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index"},
            constraints: new { id = @"([0-9]+)" }
        );

Note that the route you gave in the question should match the rule you have currently so I'd double check your controller, action and spelling in case there is simply a typo there somewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM