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:
- Centralized routing and
- 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.
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
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.
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.
Step 3
Add the student class.
In this class we will set the property of the student.
- public class Student
- {
- public int Id { get; set; }
- public string Name { get; set; }
- }
Step 4
Add the Player class.
In this class we will set the property of the Player.
- public class Player
- {
- public int student { get; set; }
- public string Name { get; set; }
- }
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.
- public class Startup
- {
- public void Configuration(IAppBuilder appBuilder)
- {
-
- HttpConfiguration config = new HttpConfiguration();
-
- config.MapHttpAttributeRoutes();
-
- config.Routes.MapHttpRoute(
- name: "players",
- routeTemplate: "api/student/{teamid}/players",
- defaults: new { controller = "student" }
- );
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
-
- appBuilder.UseWebApi(config);
- }
- }
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading.Tasks;
- using System.Web.Http;
-
- namespace RoutingApps
- {
- public class StudentController : ApiController
- {
- private static List<Student> student = new List<Student>{
- new Student{Id=1,Name="rajeev"},
- new Student{Id=2,Name="ranjan"},
- new Student{Id=3,Name="Jasmine" },
- new Student{Id=4,Name="Manish"}
- };
- private static List<Player> players = new List<Player>{
- new Player { student=1, Name="football"},
- new Player { student=2, Name="vollyball"},
- new Player { student=3, Name="Baseball"},
- new Player { student=4, Name="Rugby"}
-
- };
- public IEnumerable<Student> GetAll()
- {
- return student;
- }
- public Student GetById(int id)
- {
- var stud = student.FirstOrDefault(x => x.Id == id);
- if (stud == null)
- {
- throw new HttpResponseException(HttpStatusCode.NotFound);
- }
- return stud;
- }
- public IEnumerable<Player> GetPlayers(int teamId)
- {
- var play = players.Where(x => x.student == teamId);
- if (play == null) throw new HttpResponseException(HttpStatusCode.NotFound);
-
- return play;
- }
- }
- }
Step 7
Run the application.
- using Microsoft.Owin.Hosting;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Http;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace RoutingApps
- {
- class Program
- {
- static void Main()
- {
- string baseAddress = "http://localhost:9000/";
-
-
- using (WebApp.Start<Startup>(url: baseAddress))
- {
-
- HttpClient client = new HttpClient();
- Console.WriteLine();
- Send(HttpMethod.Get, client, baseAddress + "api/student");
- Send(HttpMethod.Get, client, baseAddress + "api/student/1");
- Send(HttpMethod.Get, client, baseAddress + "api/student/1/players");
-
-
-
-
- }
-
- Console.ReadLine();
- }
- private static void Send(HttpMethod method, HttpClient client, string url)
- {
- var msg = new HttpRequestMessage(method, url);
- var response = client.SendAsync(msg).Result;
- if (response.IsSuccessStatusCode)
- Console.WriteLine(response.Content.ReadAsStringAsync().Result);
- else
- Console.WriteLine(response.StatusCode);
-
- Console.WriteLine();
- }
- }
- }
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