jeudi 19 novembre 2015

Why does Url.RouteUrl Requires Optional Parameter and Ignores RouteName?

Here is my route configuration. Given 2 Routes that take in different parameters, Test1Route works perfectly fine as I'd expect.

        routes.MapRoute(
            name: "Test1Route",
            url: "{controller}/{action}/{optionalParam}",
            defaults: new { controller = "Test1Controller", action = "Index", optionalParam = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "Test2Route",
            url: "{controller}/{action}/{param1}/{optionalParam}",
            defaults: new { controller = "Test2Controller", action = "Index", param1 = 10, optionalParam= UrlParameter.Optional }
        ); 

But Test2Route, when added like this, completely fails using RouteUrl:

@Url.RouteUrl("Test2Route", new {action = "SomeAction", param1 = 5})

The url it makes may be: http://site/Test1Controller/ but no parameters show up so this is invalid. Debugging I may get an exception like:

A public action method '5' was not found on controller Test1Controller

Why would it be using Test1Controller when I specifically name it "Test2Route"? If I omit the name and use something incorrect - it throws an exception saying that the named route can't be found. That makes sense. But yet when specified correctly, its ignoring the name!

Lets say I go ahead and explicitly name the controller:

@Url.RouteUrl("Test2Route", new {controller = "Test2Controller", action = "SomeAction", param1 = 5})

The url becomes http://site/Test2Controller/ with no parameters. Same exception about action method not found but with Test2Controller.

Now, lets say I explicitly name optionalParam which I expect not to have to do.

@Url.RouteUrl("Test2Route", new {controller = "Test2Controller", action = "SomeAction", param1 = 5, optionalParam = 6})

The result is correct and works!

http://site/Test2Controller/5/6

  • What could be causing the Routes to default over to Test1Route despite the Test2Route being specified explicitly in the RouteUrl call?
  • Why do I need to explicitly use controller and optionalParam in the parameters? This SO demonstrates that it was necessary for someone else, but no workaround or why.

Note that upon researching, I've found some SOs that mention SomeAction didn't have [HttpGet] or [HttpPost] or both or shouldn't have either specified. I've tried all combinations regarding those flags and they seem irrelevant to the parameter issue I'm experiencing.

Also note that the routing works if I'm not using RouteUrl. Typing out http://site/Test2Controller/500/ or http://site/Test2Controller/500/600 works fine too.

Aucun commentaire:

Enregistrer un commentaire