Getting Started With ASP.Net Web API 2 : Day 12

Introduction

In this article and future articles we will be learning the Web API routing mechanism. As we know the Web API has the following two types of routing mechanisms:

  1. Centralized routing and
  2. Direct (Attribute ) routing

In this article we will learn the centralized route. the the basic terminology behind the declaring of routes in a single page, these things we will be covered.

Routing is the mechanism where a Web API matches a URI to an action. The Web API routing is very simple to MVC routing but has little difference, the Web API uses the HTTP methods and MVC uses the URI paths for the selection of the action. 

  1. config.Routes.MapHttpRoute(  
  2.                name: "DefaultApi",  
  3.                routeTemplate: "api/{controller}/{id}",  
  4.                defaults: new { id = RouteParameter.Optional }  
  5.            );  
In the Web API a controller is a class that handles the HTTP request and the public method of the controller handles the action method. When the Web API receives a request, it routes the request to an action.   

Route Table

The Routing table determines which action is invoked. As in my previous articles we have learned something about the route table using a self-hosting application.

In this application, I have set the routing table directly on the HttpSelfHostingConfiguration object. Each request in the routing table contains a route template. The defults route template for Web API is:

"api/{controller}/{id}

api is the literal path, controller and id are placeholder variables.

Whenever any request comes and the Web API framework receivers a HTTP request, the request tries to match the URI against one of the route templates in the routing table. Just suppose no route is found then the client receives the 404 error. If a matching request is found then the Web API selects the Controller.

Once the controller is found, the Web API adds the Controller to the value of the {controller} variable. Now the Web API looks at the HTTP method and then looks for an action whose name begins with the Http method name.         

Let's try to understand using code.

Step 1

Create a console application.

To create a console application we need to use a basic procedure. Click on the File menu and choose New, then click Project. After getting the project we need to specify the language from the installed templates, so we will choose Visual C#, and click Windows and then click Console Application. Now can gave the nice name of the application.

RoutingApp

Step 2

Add the Web API and OWIN Packages.

There are two ways to install the OWIN package using the Nuget Package manager. First we need to only right-click on the Project from the Solution Explorer and select the NuGet Package Manager and search the OWIN self-host package. We are able to see many applications listed below. In those we need to select the appropriate package. Secondly we need to click on the Tools menu, then click Library Package Manager, then click Package Manager Console. In the Package Manager Console window, enter the following command:

Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

Using this command we will able to install the WebAPI OWIN selfhost package and all the required OWIN packages.

PackagesOwin

Step 3

Add the student class.

In this class we will set the property of the student.

  1. public  class Student  
  2.     {  
  3.         public int Id { getset; }  
  4.         public string Name { getset; }    
  5.     }  

 Step 4

Add the Player class.

In this class we will set the property of the Player.

  1. public class Player  
  2.     {  
  3.         public int student { getset; }  
  4.         public string Name { getset; }  
  5.     }  

 Step 5 

Configure the Web API for the self-hosting.

In this step we will add a class that handles the route as well as make the compatible route to travel according to the URL parameter. For that right-click on the project and select Add / Class to add a new class. Name the class Startup. In this class we will configure the routes of a specific controller and specify the routeTemplate to the API.  

  1. public class Startup  
  2.     {  
  3.         public void Configuration(IAppBuilder appBuilder)  
  4.         {  
  5.             // Configure Web API for self-host.     
  6.             HttpConfiguration config = new HttpConfiguration();  
  7.   
  8.             config.MapHttpAttributeRoutes();  
  9.   
  10.             config.Routes.MapHttpRoute(  
  11.                 name: "players",  
  12.                 routeTemplate: "api/student/{teamid}/players",  
  13.                 defaults: new { controller = "student" }  
  14.             );  
  15.             config.Routes.MapHttpRoute(  
  16.                 name: "DefaultApi",  
  17.                 routeTemplate: "api/{controller}/{id}",  
  18.                 defaults: new { id = RouteParameter.Optional }  
  19.             );  
  20.   
  21.             appBuilder.UseWebApi(config);  
  22.         }  
  23.     }  

 Step 6

Now to add a Web API controller.

Now add a Web API controller class. Right-click the project and select Add / Class to add a new class. Name the class StudentController. In this controller we are getting the the records in three ways. In the first way we are getting all the records, in the second way we are getting the records using the id and we pass the specific id and in third case we are getting the records by a different class on the basis of id filtration. 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7. using System.Web.Http;  
  8.   
  9. namespace RoutingApps  
  10. {  
  11.     public class StudentController : ApiController  
  12.     {  
  13.         private static List<Student> student = new List<Student>{    
  14.            new Student{Id=1,Name="rajeev"},    
  15.            new Student{Id=2,Name="ranjan"},    
  16.            new Student{Id=3,Name="Jasmine" },    
  17.            new Student{Id=4,Name="Manish"}    
  18.        };  
  19.         private static List<Player> players = new List<Player>{    
  20.           new Player { student=1, Name="football"},  
  21.           new Player { student=2, Name="vollyball"},  
  22.           new Player { student=3, Name="Baseball"},  
  23.           new Player { student=4, Name="Rugby"}  
  24.   
  25.        };  
  26.         public IEnumerable<Student> GetAll()  
  27.         {  
  28.             return student;  
  29.         }  
  30.         public Student GetById(int id)  
  31.         {  
  32.             var stud = student.FirstOrDefault(x => x.Id == id);  
  33.             if (stud == null)  
  34.             {  
  35.                 throw new HttpResponseException(HttpStatusCode.NotFound);  
  36.             }  
  37.             return stud;  
  38.         }  
  39.         public IEnumerable<Player> GetPlayers(int teamId)  
  40.         {  
  41.             var play = players.Where(x => x.student == teamId);  
  42.             if (play == nullthrow new HttpResponseException(HttpStatusCode.NotFound);  
  43.   
  44.             return play;  
  45.         }  
  46.     }  
  47. }  
Step 7

Run the application. 
  1. using Microsoft.Owin.Hosting;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Net.Http;  
  6. using System.Text;  
  7. using System.Threading.Tasks;    
  8.   
  9. namespace RoutingApps  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main()  
  14.         {  
  15.             string baseAddress = "http://localhost:9000/";  
  16.   
  17.             // Start OWIN host     
  18.             using (WebApp.Start<Startup>(url: baseAddress))  
  19.             {  
  20.                 // Create HttpCient and make a request to api/values     
  21.                 HttpClient client = new HttpClient();  
  22.                 Console.WriteLine();  
  23.                 Send(HttpMethod.Get, client, baseAddress + "api/student");  
  24.                 Send(HttpMethod.Get, client, baseAddress + "api/student/1");  
  25.                 Send(HttpMethod.Get, client, baseAddress + "api/student/1/players");  
  26.   
  27.                 
  28.                 //Console.WriteLine(response);  
  29.                 //Console.WriteLine(response.Content.ReadAsStringAsync().Result);  
  30.             }  
  31.   
  32.             Console.ReadLine();  
  33.         }  
  34.         private static void Send(HttpMethod method, HttpClient client, string url)  
  35.         {  
  36.             var msg = new HttpRequestMessage(method, url);  
  37.             var response = client.SendAsync(msg).Result;  
  38.             if (response.IsSuccessStatusCode)  
  39.                 Console.WriteLine(response.Content.ReadAsStringAsync().Result);  
  40.             else  
  41.                 Console.WriteLine(response.StatusCode);  
  42.   
  43.             Console.WriteLine();  
  44.         }  
  45.     }  
  46. }  

 Output

output

Summary

In this article we learned the Web API routing mechanism and understand the centralized routing concepts using an example. Future articles will be on Direct (Attribute) routing. So keep learning.

<< Getting Started With ASP.Net Web API 2 : Day 11

Up Next
    Ebook Download
    View all
    Learn
    View all