Routing System in Web API

Introduction

In the Web API all HTTP requests pass through the routing system that decides what will manage the request. The main purpose of a routing system is to decide which action of which controller should be called to mange the actual request.
 
When we create a simple Web API application the template generates a default route for us in the following:
  1. namespace route_routeprifx {  
  2.     public static class WebApiConfig {  
  3.         public static void Register(HttpConfiguration config) {  
  4.   
  5.             config.MapHttpAttributeRoutes();  
  6.   
  7.             config.Routes.MapHttpRoute(  
  8.             name: "DefaultApi",  
  9.             routeTemplate: "api/{controller}/{id}",  
  10.             defaults: new {  
  11.                 id = RouteParameter.Optional  
  12.             });  
  13.         }  
  14.     }  
  15. }  
The method config.Routes.MapHttpRoute contains the three parameters.
  1. A route name ("DefaultApi").

  2. A route Template: A template with API and two placeholders (controller and id).

  3. Defaults values: In this case, we are saying that the id is not mandatory in the request.
If you have used ASP.NET MVC then you will find several similarities. In MVC a route template action is present and here the action is not present, this is the main difference between the two routing systems in the Web API, the action is determined by the HTTP method.
 
The default route pattern for an ASP.Net MVC project is defined as follows: 
  1. routes.MapRoute(  
  2. name: "Default"//route name  
  3. url: "{controller}/{action}/{id}"//route pattern  
  4. defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional} //parameter default values  
  5. );  
If the routing system does not find a correct match then it will retrun a HTTP status 404 Not Found.
 
To decide which action should be called, the routing system must analyze the HTTP method. If we place a GET request to the server, the action should be something like GetResource(). If we place a POST, the action should be something like PostResource().
 
When modifying or adding new routes in our project.
  1. amespace routwork  
  2. {  
  3.     public static class WebApiConfig  
  4.     {  
  5.         public static void Register(HttpConfiguration config)  
  6.         {  
  7.             // Web API configuration and services  
  8.             // Configure Web API to use only bearer token authentication.  
  9.             config.SuppressDefaultHostAuthentication();  
  10.             config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));  
  11.   
  12.             // Web API routes  
  13.             config.MapHttpAttributeRoutes();  
  14.   
  15.             config.Routes.MapHttpRoute(  
  16.                 name: "DefaultApi",  
  17.                 routeTemplate: "api/{controller}/{id}",  
  18.                 defaults: new { id = RouteParameter.Optional }  
  19.             );  
  20.   
  21.             config.Routes.MapHttpRoute(  
  22.             name: "GetAllEmploye",  
  23.             routeTemplate: "api/values/GetAll",  
  24.             defaults: new { controller = "Values", action = "GetAll", id = UrlParameter.Optional }  
  25.   
  26.             );  
  27.             config.Routes.MapHttpRoute(  
  28.             name: "Getdetail",  
  29.             routeTemplate: "api/values/Getdetail/{id}",  
  30.             defaults: new { controller = "Values", action = "Getdetail", id = UrlParameter.Optional }  
  31.   
  32.             );  
  33.   
  34.             config.Routes.MapHttpRoute(  
  35.             name: "GetEmployeDetailByTest",  
  36.             routeTemplate: "api/values/GetEmployeDetailByTest/{id}",  
  37.             defaults: new { controller = "Values", action = "GetEmployeDetailByTest", id = UrlParameter.Optional }  
  38.   
  39.             );  
  40.   
  41.         }  
  42.     }  
  43. }  
Here we have three new route names of all the new routes. They are not the same and all route templates contain various placeholders and in all the routes the id is optional.
 
To see the example working, we define a new ValuesController like this:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7.   
  8. using routwork.Models;  
  9.   
  10. namespace routwork.Controllers  
  11. {  
  12.   
  13.      
  14.     public class ValuesController : ApiController  
  15.     {  
  16.         // GET api/values  
  17.         [HttpGet]  
  18.         [ActionName("GetAll")]  
  19.         
  20.         public List<Employe> GetAllEmploye()  
  21.         {  
  22.             List<Employe> emplist = new List<Employe>();  
  23.             emplist.Add(new Employe  
  24.             {  
  25.   
  26.                 Empid = 1,  
  27.                 Empname = "atul",  
  28.   
  29.   
  30.             });  
  31.             emplist.Add(new Employe  
  32.             {  
  33.   
  34.                 Empid = 2,  
  35.                 Empname = "taj",  
  36.   
  37.   
  38.             });  
  39.             return emplist;  
  40.         }  
  41.   
  42.   
  43.         [ActionName ("Getdetail")]  
  44.         public Employe GetEmployeDetail(int id)  
  45.         {  
  46.   
  47.             return new Employe  
  48.             {  
  49.   
  50.                 Empid = 1,  
  51.                 Empname = "atul"  
  52.   
  53.             };  
  54.   
  55.         }  
  56.   
  57.        
  58.         public Employe GetEmployeDetailByTest(int id)  
  59.         {  
  60.   
  61.             return new Employe  
  62.             {  
  63.   
  64.                 Empid = 2,  
  65.                 Empname = "taj"  
  66.   
  67.             };  
  68.   
  69.         }  
  70.     }  
  71. }  
URI ID
GET api/values/GetAll N/A
GET api/values/Getdetail/1 1
GET api/values/GetEmployeDetailByTest/2 2

Let us see the output of the related URL.
 
1. api/values/GetAll
 
2. api/values/Getdetail/1

3. api/values/GetEmployeDetailByTest/2
 
Above all calls is GET calls. If we try to POST to this URL we obtain the following error:
 
The requested resource does not support http method 'POST'
 
The possible attributes that match all the HTTP methods are: 
  • HttpGet
  • HttpPost
  • HttpPut
  • HttpOptions
  • HttpPatch
  • HttpDelete
  • HttpHead
Summary

In this article we learned how to use routing in the Web API and the difference between ASP.Net MVC and Web API Routing.

Up Next
    Ebook Download
    View all
    Learn
    View all