Vitor Canova Vitor Canova - 3 months ago 21
ASP.NET (C#) Question

Is there a way to make URL parameter in MapRoute being take into account in ActionLink?

I built an web application where the

RouteConfig.cs
was the default one.

Now I received a task where I need to append a customer tracking ID in the beginning of the URL but keeping the same functionality it has when it is not present too.


http://localhost:60202/Home/Index //Generic customer
http://localhost:60202/Location/123/Home/Index //URL with the customer tracking id


This code
123
is a tracking ID where my customer knows the location he originates the call to my page. I have no power to ask them to change this since they use across the globe.

I tried to achieve this with this custom route:

routes.MapRoute(
name: "Route",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);


routes.MapRoute(
name: "Default",
url: "Location/{trackingId}/{controller}/{action}",
defaults: new { trackingId = 0, controller = "Home", action = "Index" }
);


In this case I can access my application with both URL schema I provided above but I couldn't manage to make
ActionLink
and
BeginForm
take this into account.

@Html.ActionLink("InĂ­cio", "Index", "Home") //this should have full URL info


Is there a way to achieve this without the need to change every
ActionLink
,
Url.Content
and
BeginForm
and surround them with
if
in every case?

How could I use both URL schema without change every navigation code?

Our currently implemented approach is to duplicated the folders in IIS since there is only 4 as of today but in near future it can be a pain to maintain.

I don't know why but based on this question it should work out of the box.

Edit 1

Looks like changing position of these two
MapRoute
are making the
ActionLink
work as I expected. Unfortunately
Url.Content
still is buggy.

Answer

Well, it's embarrassing but looks like the order you add routes make difference. So I changed to this:

routes.MapRoute(
    name: "Default",
    url: "Location/{trackingId}/{controller}/{action}",
    defaults: new { trackingId = 0, controller = "Home", action = "Index" }
);

routes.MapRoute(
    name: "Route",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

With this change every ActionLink started to work as I expected. I still had the problem with Url.Content I was using in Ajax calls.

In this case I figured out that I should use Ulr.Action for this instead.

Referenced js and css still used the second MapRoute (or don't even care about the route at all) but this is not a problem.