Recently I came across this question:
I have this route from RouteConfig
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"",
"{controller}/{action}/{productName}",
new
{
action = "Show",
productName = "aaaa"
}
);
}
Now they need to add a routing to make sure all products that's no longer exist or have IDs changed will be displayed to a product.
The recommended solution is to have:
routes.MapRoute(
"Product",
"Product/{action}/{productName}",
new { action = "Show", productName = "aaa" }
);
but with no controller in the default value for route, it will throw an exception of
The matched route does not include a 'controller' route value, which is required.
So it is possible to define a route with default routing but no controller specified?
Stephen is correct, it is not possible to make a route without specifying controller. However, it is possible to use a default controller value and not pass the value for {controller}
in the URL.
routes.MapRoute(
"Product",
"Product/{action}/{productName}",
new { controller = "Product", action = "Show", productName = "aaa" }
);
Also, you should be careful how you specify your other defaults. What you have defined here are optional values for action
and productName
, which default to what you specified in the defaults
.
Therefore, the following URLs will function:
/Product
/Product/Show
Usually it doesn't make any sense to make a "default" product. It would make more sense to make action
and productName
into required parameters in the URL.
routes.MapRoute(
"Product",
"Product/{action}/{productName}",
new { controller = "Product" }
);