Routing in WebAPI is very similar to routing in MVC. In MVC application routing maps a URL to action methods in Controller.Similarly in WebAPI routing is used to map a URL to action method in Controller.
In a WebAPI project routing is defined in the file WebApiConfig.cs in the App_Start folder.By default following route is defined in the WebApiConfig file
public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
There are few important things to note in the WebApiConfig file
1.It imports the System.Web.Http namespace instead of using System.Web.Mvc unlike RouteConfig class in MVC
using System.Web.Http
2.It uses the MapHttpRoute method for adding the routes to the routing table.It is MapRoute method in MVC.
config.Routes.MapHttpRoute()
3.Route template does not include the action method name as in the case of MVC.
routeTemplate: "api/{controller}/{id}"
Instead of declaring action method name as a segment variable the action method is selected based on the HTTP method used to make the request.Though we can also include the action method name in a route if required as:
api/{controller}/{action}/{id}
In this case action method is explicitly specified and the route will map to URLs which includes action method name in URL.
4.Route template has api prefix.This is to distinguish WebAPI URL from the MVC URL.
Leave a Reply