user1938415
user1938415

Reputation: 21

UrlHelper.Action method not mapping to correct route with first variable parameter

Let's look at these two routes mapped in RouteConfig.cs, one with a guid and one without:

// Non-guid route
routes.MapPageRoute(
    name: null,
    url: "dashboard/{action}",
    defaults: new { controller = "Dashboard", action = "Index" }
);
// Guid route
routes.MapPageRoute(
    name: null,
    url: "{guid}/dashboard/{action}",
    defaults: new { controller = "Dashboard", action = "Index" }
);

And the method call:

UrlHelper.Action("Index", "Dashboard", new { guid = "c73b47b9-4ad5-414a-a92e-8937231f8e2bD" })

The method returns this:

"/dashboard/?guid=c73b47b9-4ad5-414a-a92e-8937231f8e2b"

But I'm expecting this:

"/c73b47b9-4ad5-414a-a92e-8937231f8e2b/dashboard/"

Note that it's putting the guid as a querystring value instead of the first parameter.

Now if I hardcode that second url the app uses the correct guid route and also works if I use route names instead (UrlHelper.RouteUrl) so I don't think it's an issue with the route mappings themselves. Neither of these solutions will work well with our application as we have hundreds of routes and currently using UrlHelper.Action all over the place.

I've also tried pretty much every overload and variation of UrlHelper.Action, including passing a RouteValueDictionary instead of an anonymous object.

This is an ASP.NET MVC 4 web application.

Any ideas to why this isn't working? (or alternatives, maybe using one route)

Upvotes: 2

Views: 476

Answers (1)

Ionian316
Ionian316

Reputation: 2343

Try this. Put the more specific route first:

routes.MapRoute(
    name: "WithGUID",
    url: "{guid}/dashboard/{action}",
      defaults: new { controller = "Dashboard", action = "Index" }
);

routes.MapRoute(
    name: "NoGUID",
    url: "dashboard/{action}",
      defaults: new { controller = "Dashboard", action = "Index", guid = "" }
);

Upvotes: 1

Related Questions