views:

68

answers:

1

I am working with ASP.NET MVC 2 and would like to optimize my routing. The desired result is as follows:

http://www.url.com/Sites/
http://www.url.com/Sites/Search/NY001
http://www.url.com/Sites/NY001
http://www.url.com/Sites/NY001/Photos

The problem with this scenario is that I want to treat the URL bits differently depending on their content, in a sense. As one can imagine, "NY001" is the identifier for a specific site, not for an action that lives in the Sites controller. My current solution is to define a special route map for the site-specific URLs and to specify each action in the Sites controller separately before that.

// currently in place, works
routes.MapRoute("SiteList", "Sites", new { controller = "Sites", action = "Index" });
routes.MapRoute("SiteSearch", "Sites/Search/{searchString}", new { controller = "Sites", action = "Index", searchString = "" });
routes.MapRoute("SiteNotFound", "Sites/NotFound", new { controller = "Sites", action = "NotFound" });
// and so on...

routes.MapRoute("Site", "Sites/{siteId}/{action}", new { controller = "Sites", action = "Index", siteId = "" });

As this is one of the central components of my web application, these actions are growing daily and the list is getting a bit unwieldy. I would love to be able to distill the long list of action-specific routes to a single declaration, similar to this:

routes.MapRoute("Sites", "Sites/{action}/{id}", new { controller = "Sites", action = "Index", id = UrlParameter.Optional });

The problem is that the routing framework has no way of differentiating between this new route and the site-specific one in the above example; therefore, both are matches. Am I stuck with declaring each action separately? Should I consider using a regular expression to differentiate based on the URLs' content?

Thanks in advance and I apologize in advance if this question has already been asked in a different form.

A: 

Not sure what exactly you want to accomplish. Of course you can't really map URLs with different signatures with one route, but you can reduce the list like this:

routes.MapRoute("Site", "Sites/{siteId}/{action}", new { controller = "Sites", action = "Index" }, new { action = "(?:Index|Photos|News)", siteId = @"[A-Z0-9]+" });

for urls:

http://www.url.com/Sites/NY001
http://www.url.com/Sites/NY001/Photos
http://www.url.com/Sites/NY001/News

This route will only map to actions Index, Photos, News (and whatever else you put in that reg. expression).

Necros