12

I want to make an MVC route for a list of news, which can be served in several formats.

  • news -> (X)HTML
  • news.rss -> RSS
  • news.atom -> ATOM

Is it possible to do this (the more general "optional extension" situation crops up in several places in my planned design) with one route? Or do I need to make two routes like this:

routes.MapRoute("News-ImplicitFormat",
                "news",
                new { controller = "News", action = "Browse", format = "" });

routes.MapRoute("News-ExplicitFormat",
                "news.{format}"
                new { controller = "News", action = "Browse" });

It seems like it would be useful to have the routing system support something like:

routes.MapRoute("News",
                "news(.{format})?",
                new { controller = "News", action = "Browse" });
Doug McClean
  • 14,265
  • 6
  • 48
  • 70

2 Answers2

13

I made a method to support adding pairs like this as follows:

public static void MapRouteWithOptionalFormat(this RouteCollection routes,
                                              string name,
                                              string url,
                                              object defaults)
{
    Route implicitRoute = routes.MapRoute(name + "-ImplicitFormat",
                                          url,
                                          defaults);
    implicitRoute.Defaults.Add("format", string.Empty);

    Route explicitRoute = routes.MapRoute(name + "-ExplicitFormat",
                                          url + ".{format}",
                                          defaults);
}
Doug McClean
  • 14,265
  • 6
  • 48
  • 70
  • 1
    This works well, though I switched the order of the implicit and explicit routes, due to the explicit being more specifiable. – ern May 26 '10 at 15:57
0

You can look into using constraints to make this work with normal routes.

UPDATE: actually, I misread the question. The other answer is the correct thing to do for now. Or create a custom route. We're looking at the idea of optional segments as a possible future feature.

Haacked
  • 58,045
  • 14
  • 90
  • 114
  • Phil, what would I be looking to constrain? .Contains(".")? Could you outline this strategy briefly? Awesome work, by the way. Thanks! – Doug McClean Nov 02 '08 at 17:51
  • Phil Haack getting downvoted on an MVC question, I bet that doesn't happen too often :) – fearofawhackplanet May 18 '11 at 14:18
  • 2
    I know this is 2-3 years old, but is this doable now? I was wondering if I can have `/post/15` = html, `/post/15.json` = json api-data. – Alxandr Jun 24 '11 at 11:05
  • Oh, and I want them to go to different routes based on the ending, so that I can have API-controllers. – Alxandr Jun 24 '11 at 11:11