Ray Cheng
Ray Cheng

Reputation: 12566

How to create a route without action?

Is it possible to create a route without action?

I have this default route:

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

But I also I want to have URLs like this: http://mysite/bar/1234 where 1234 is the ID and bar is the controller.

So I created the following route:

routes.MapRoute(
    name: "BarRoute",
    url: "{controller}/{id}",
    defaults: new { controller = "bar", action = "Index", id = UrlParameter.Optional }
);

But when I navigate to http://mysite/bar/1234, it said the resource is not found. What did I do wrong in the second route?

Upvotes: 3

Views: 1389

Answers (2)

jwaliszko
jwaliszko

Reputation: 17064

routes.MapRoute(
  name:        "BarRoute",
  url:         "{controller}/{id}",
  defaults:    new { controller = "Bar", action = "Index" },
  constraints: new { id = @"\d+" }
);

You have to take into account that your route has to be placed in appropriate place - before the more general routes, for example:

routes.MapRoute(
           name: "BarRoute",
routes.MapRoute(
           name: "Default",

Upvotes: 5

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You cannot have the following 2 routes in that order without any constraints

  • {controller}/{action}/{id}
  • {controller}/{id}

Those 2 routes are incompatible. When you attempt to access http://mysite/bar/1234, the routing engine is analyzing your routes and /bar/1234 matches your first route. Except that I guess you do not have an action called 1234 on the Bar controller.

So if you want this setup to work you need to specify some constraints. Also don't forget that the order of your routes definition is important because they are resolved in the order you defined them. So make sure you place more specific routes at the top.

Upvotes: 3

Related Questions