mgmedick
mgmedick

Reputation: 700

MVC route config same url paramater signature

I'm having an issue with my route config (MVC 5). I have multiple routes with the same parameter signature (same amount of parameters and parameter type).

In the code below the bottom 2 config settings are butting heads. Normal post backs to the server are supposed to get the default path at the bottom, but instead grab the one in the middle, due to the same same signature.

I can't figure out a way to make the middle one unique from the default one at the bottom. I still need the middle one to only have those 2 strings (action and gameHtmlAbbr).

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

        routes.MapRoute(
            name: null,
            url: "{gameConsoleHtmlAbbr}",
            defaults: new { Controller = "Game", action = "GameList", gameConsoleHtmlAbbr = (string)null }
        );

        routes.MapRoute(
            name: null,
            url: "{action}/{gameHtmlAbbr}",
            defaults: new { Controller = "Game", action = "Snes", gameHtmlAbbr = (string)null }
        );

        routes.MapRoute(
            name: null,
            url: "{controller}/{action}",
            defaults: new { controller = "Game", action = "GameList" }
        );
    }
}

Upvotes: 0

Views: 244

Answers (1)

user3559349
user3559349

Reputation:

Both you 2nd and 3rd routes define a route with 2 segments (but nothing to distinguish between them) and because routes are matched in the order they are defined, any url with 2 segments will match the 2nd (and the 3rd route will never be executed)

You need to define a specific route for each method, for example to hit the Snes() method of GameController, add a specific route before the default route (and delete your 2nd route

routes.MapRoute(
    name: "Snes",
    url: "Snes/{gameHtmlAbbr}",
    defaults: new { Controller = "Game", action = "Snes", gameHtmlAbbr = (string)null }
);

Upvotes: 1

Related Questions