Fix “No Route in the Route Table Matches the Supplied Values” in ASP.NET MVC 5
Quick fix. Check the registered route name and supply every required value that has no default. In MVC 5, Url.RouteUrl is a useful way to test outbound URL generation before returning a redirect.
This guide applies to ASP.NET MVC 5 on .NET Framework (System.Web.Mvc).
Tell inbound routing from URL generation
A browser can reach an action while another action fails to generate a URL to it. The exception can occur after the controller returns a RedirectToRouteResult. If the stack trace points to its ExecuteResult method, inspect the route name and the values passed to RedirectToRoute. A route name identifies a registered route, whereas an action name identifies an action method.
Match the route’s required keys
Put the specific route before broader routes in RouteConfig.RegisterRoutes. This example assumes a ProductsController.Details(string slug) action and an established controller action that has just obtained a valid product slug. A route that contains {slug} needs the slug key. Passing an id alone will not satisfy it.
// RouteConfig.RegisterRoutes
routes.MapRoute(
name: "ProductDetails",
url: "products/{slug}",
defaults: new { controller = "Products", action = "Details" });
// In the source action, after obtaining the product slug
var values = new { slug = "steel-shelf" };
var target = Url.RouteUrl("ProductDetails", values);
if (String.IsNullOrEmpty(target))
throw new InvalidOperationException("ProductDetails could not generate a URL.");
return RedirectToRoute("ProductDetails", values);
Check constraints, areas, and startup
A route constraint can reject an outbound value as well as an inbound request. Try a known valid slug, check that startup calls RegisterRoutes, and confirm that MVC 5 attribute routes are mapped if your named route uses [Route]. When generating a link across areas with conventional routing, supply the destination area explicitly when required. Use area = "" for a root-area action when the ambient area would otherwise be inherited.
Verify the redirect and the destination
Inspect the redirect’s Location header. Under the application root the example should end in /products/steel-shelf. Follow that URL and confirm the intended action runs. Test from both the root and any area that normally invokes the source action.
Comments
Post a Comment