marifemac marifemac - 23 days ago 6
C# Question

What is the difference between the way routes are registered with MVC and Web API?

In my MVC and WebAPI application I see two different ways of doing routes.


  • One for MVC which calls RegisterRoutes and passes RouteTable.Routes

  • One for Web API which calls CustomizeConfig and passes GlobalConfiguration.Configuration.



For WebAPI:

WebApiConfig.CustomizeConfig(GlobalConfiguration.Configuration);

public static void Register(System.Web.Http.HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: ApiControllerOnly,
routeTemplate: "api/{controller}");
}


For MVC:

RouteConfig.RegisterRoutes(RouteTable.Routes);

public static void RegisterRoutes(System.Web.Routing.RouteCollection routes)
{
routes.MapRoute("DefaultRedirect",
"",
new { controller = "Home", action = "Index" });
}


Can someone explain if there is any difference in me registering my routes in one or the other method calls? Also why is it done this way with one using.

Answer

MVC routes register with ASP.NET (system.web) route collection. Web API however is designed to run either in IIS on top of system.web or as a self host without changing the code.

Hence Web API has a different registration mechanism, where it can use the system.web routing under the hood, or it's own routing system when using self hosting (Either WCF self host, or Owin host are supported out of the box).

There is one other small difference, Web API routes require naming of the route, where MVC routes do not.