2

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.

Mintu Anil
  • 73
  • 5

3 Answers3

0

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>
Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265
0

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.

dove
  • 20,469
  • 14
  • 82
  • 108
  • I tried this but getting the same error, when i am trying to access http://example.com/controllername/action/166699406 – Mintu Anil Jun 18 '14 at 11:21
  • I'm guessing there is something wrong with that url, try writing a simple test to verify your routes: https://www.nuget.org/packages/MvcRouteTester.MVC5/ – dove Jun 18 '14 at 11:24