Introduction
In this article, we will define how the ASP.Net Web API transfers the HTTP request to the controller.
Routing Table
We use controllers in the ASP. Net Web API. These controllers work as a class for handling the HTTP request. After receiving the request by the API framework it transfers the request to perform an action. The controller class has public methods; these methods are called action methods.
We use the routing table to determine the action to be performed depending on that action being called. By default the Visual Studio creates a default route for the web API.
- public static void Register(HttpConfiguration config)
- {
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{Id}",
- defaults: new { Id = RouteParameter.Optional }
- );
- }
We defined this route in the Web.Config.cs file:
We know that the web API is a framework that receives the HTTP request for performing the action. After receiving the request it matches the URI of the route templates to the routing table. If there is not a match then it returns the error to the client. For example, there are various URI matches to the default route:
- /api/products/
- api/products/1
- api/Items/
- /products/1
If the route matching is done then the Web API selects the controller and action.
- To find the controller the Web API adds the controller for the value of its variable.
- To find the action the Web API first sees the HTTP method and the action. It matches the method's begin name with the HTTP method name. For example if there is a Get request, then the Web API sees the action and verifies that the action starts with Get.... such as GetAllItems, GetProducts. And then applies the Get method.
- And the other variables in the route template work as an action parameter.
- public class Items : ApiController
- {
- public void GetAllItems() { }
- public IEnumerable<Item> GetItemsById(int Id) { }
- public HttpResponseMessage DeleteItem(int Id){ }
- }
Here are some HTTP requests with actions:
| HTTP Method | URI Path | Action | Parameter |
| GET | api/items | GetAllItems | none |
| GET | api/items/3 | GetItemsById | 3 |
| DELETE | api/items/3 | DeleteItem | 3 |
| POST | api/items | no match |

Comments
Join the conversation! Your thoughts help the community grow.