Search code examples
asp.net-mvcurlurl-rewritingasp.net-mvc-routing

ASP.NET MVC routing: 2 route for same page, how to give same url rendered?


I generate some url for a list, and when the id match as certain string, i d like to call another route than the default "article" one i ve managed to that. I ve got 3 routes, all working.

 routes.MapRoute(
            name:="ArticleToPage",
            url:="article-MySecondPage",
            defaults:=New With {.Controller = "MySecondPage", .Action = "MySecondPage"}
         )
    routes.MapRoute(
        name:="MySecondPage",
        url:="MySecondPage",
        defaults:=New With {.controller = "MySecondPage", .action = "MySecondPage"}
    )

routes.MapRoute(
                name:="Article",
                url:="article-{id}",
                defaults:=New With {.Controller = "Page", .Action = "Article", .id = UrlParameter.Optional}
             )

That s work s just fine, rerouting me exactly where i want.

But is there a way to call the route "MySecondPage" instead of "AticleToPage", in order to have the right url? i tried to specify route the action and several things but i m getting nowhere.. DO you know a way??

EDIT

I might not have been clear up there

i have 2 url linked to those routes sending me to the same page :

Site/MySecondPage
Site/Article-MySecondPage

When i call "Site/Article-MySecondPage" i d like it to actually reroute to my "MySecondPage" route, or convert the url within the route call (but i don t think that s possible) to "Site/MySecondPage"


Solution

  • Both of your URLs:

    Site/MySecondPage
    Site/Article-MySecondPage
    

    should be working. That is, when you call each of these URLs, your application should be running the action MySecondPage in a controller named MySecondPageController.

    If what you want is to generate a URL with the second URL, you need to use @Html.RouteLink rather than @Html.ActionLink so you can pass the name of the route to match.

    @Html.RouteLink(
        linkText:= "My Second Page 1", 
        routeName:= "ArticleToPage", 
        routeValues:= New With {.Controller = "MySecondPage", .Action = "MySecondPage"})
    @Html.RouteLink(
        linkText:= "My Second Page 2", 
        routeName:= "MySecondPage", 
        routeValues:= New With {.Controller = "MySecondPage", .Action = "MySecondPage"})