11

I've seen both being used and so I wonder, do they do the same thing or different things? If it's the latter, what's the difference?

I tried answering it myself by having a look at the visual studio MVC 4 (rc) web api template, but sadly it uses both, so my confusion remains. Here's what the template contains:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

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

1 Answer 1

16

Use RouteParameter for Web Api routes (.MapHttpRoute) and UrlParameter for standard MVC controller routes (.MapRoute). As you know standard MVC and Web API are 2 completely distinct APIs in terms of assemblies and namespaces even if both are pretty similar. You could for example self host your Web API in a console application, so you won't even have a reference to the System.Web.Mvc assembly and you would of course use RouteParameter in this case.

2
  • Aha.. I didn't even notice that they had called different methods on the routes object. But it makes sense. I wonder why they've included views and mvc stuff in the web api template. Hope they get done with the SPA template soon. Thanks! :) Jul 26, 2012 at 12:26
  • 1
    There's also different behaviour between two of these. If you check this post: stackoverflow.com/questions/19043266/… UrlParameter.Optional won't require you to specify default parameters, while RouteParameter.Optional will. Jun 17, 2015 at 7:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.