In article we will see how ASP.NET Web API routes HTTP requests to controllers. Web API routing is very similar to MVC routing. The main difference is that Web API uses the HTTP method, not the URI path, to select the action. We can also use MVC-style routing in Web API. A related difference is that Web API performs content type negotiation in response to incoming requests, and attempts to return the proper content type.
Web API route Configuration file
In a standard Web API project template, route configuration is called from RouteConfig class, and a WebApiConfig class, both in the App_Start folder.
The WebApiConfig Class
The method MapHttpRoute in this case takes three parameters:
- A route name (DefaultApi).
- A route template: A template with a literal (api) and two placeholders (controller and id) that will be replaced with the current request segments.
- Default values: In this case, we are saying that the id is not mandatory in the request.
The MapHttpRoute method simply adds a new entry in a routing table which is used by Web API. The default route that is created by template will respond to, in case of our StudentsController, these request:
MapHttpAttributeRoutes method call during configuration, to enable attribute routing. This extension method is defined in the System.Web.Http.HttpConfigurationExtensions class.
Defining our own route
Now we are defining a new route before the default one; this means that the route named StudentByDate is evaluated before the other. This new route has four placeholders: one for the controller name, and three to define a date (day, month, and year).
We define a new StudentsController like this:
The request will be parsed and decomposed to be able to call the Get action with its parameters:
We can also use a route constraint to sure that the parameters are numbers, as in the following code:
The constraints parameter uses a regular expression to be sure that month and day are two numbers (composed of zero, one, or two digits).
Routing by Action Name
As the controller’s action that has to be executed is selected by the HTTP method, so we have only seven actions available. What happens if I want more actions or a custom action name that does not start with Get, Post, and so on?
One way to achieve this behaviour is to create a route where the action name is included in the URI:
Now we Can use URI like this:
that will be mapped to the action Details in the Students controller, but this method must have an HTTP attribute that it supports:
I hope that you will have better understanding of Web API URL routing. I would like to hear valuable feedback or question from you. It encourage me to write more quality article.
Happy Reading 🙂