views:

44

answers:

3

Hey there

How do i map multiple url's to the same action in asp.net mvc

I have:

string url1 = "Help/Me";
string url2 = "Help/Me/Now";
string url3 = "Help/Polemus";
string url1 = "Help/Polemus/Tomorow";

In my global.asax.cs file i want to map all those url to the following action:

public class PageController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
}
+2  A: 

Add the following line to your routing table:

routes.MapRoute("RouteName", "Help/{Thing}/{OtherThing}", new { controller = "Page" });

EDIT:

foreach(string url in urls)
    routes.MapRoute("RouteName-" + url, url, new { controller = "Page", action = "Index" });
SLaks
this is almost exactly as what i had... i tried your second example, however, when navigating to that url i get a "resource cannot be found" error, and i do have the associated "\Views\Page\Index.aspx" view.
Dusty Roberts
Try my edit. (I forgot the action name)
SLaks
hehe, with the edit, it's now exactly the same as my initial attempt :)
Dusty Roberts
@Dusty: What are your URL strings? Make sure they have `/`, not \ (frontslash, not backslash).
SLaks
@SLaks: problem was i was mapping these routes after i mapped the default "/Controller/Action/Id" reoutes, i swapped it arround and now it works. thanx for confirming though
Dusty Roberts
+2  A: 

You can just add the routes into your route table as you need them, same as any other route. Just give them unique names, hard coded URL and point them to the same controller / action. It will work fine.

If you use pattern matching instead of hard coded URLs just make sure you get all your routes in the right order so the correct one is selected from the list. So /Help/Me should appear before /Help/{Page} if the hard coded route goes to a different page to the pattern matched one. If you put /help/{page} in the route tabel 1st this will match to /help/me and your hard coded named action for that route would never fire.

On a side note, if this is a public facing site and SEO is important please be careful if you have multiple URLs returning the same data, it will be flagged as duplicate. If this is the case, then use the Canonical tag, this gives all the page rank from all the URLS that go to that single page to the one you name and removes the duplicate content issue for you.

Paul Hadfield
A: 

http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx

Great Resource is this blog, it helped me when I was evaluating the technology

http://weblogs.asp.net/scottgu/default.aspx

Aaron Saunders