Routing In WEB API

In this article, we are going to learn the different types of routing techniques in Web API.

Nowadays Web API is a popular framework in .NET because its light weight and it is an easy way to implement a RESTful web service.

Earlier we used web form application to create the website but now everybody wants to use rest service.

We can write one business logic for the Website, Android app, iPhone app, Windows app, etc and call our web API service.

Changing of exiting functionality in Web API is also very simple, like routing.

We can do routing in three types:

  1. Global level
  2. Controller level
  3. Action level

Global level

Web API uses URI as “DomainName/api/ControllerName/Id” by default where Id is the optional parameter. If we want to change the routing globally, then we have to change routing code in register Method in WebApiConfig.cs under App_Start folder.

Global level

As shown in the image we can change the routeTemplate value as per our requirement.

If we want routing with action name then we have to change our routeTemplate as below:

    routeTemplate: "api/{controller}/{action}/{id}"

In the above code our URI is changed as:
    DomainName/api/ControllerName/ActionName/Id
We can also change the constant keyword “api” and can give any name but for differentiating between MVC controller and web API controller we are using starting as “api” Keyword.

We can globally set multiple routing in WebApiConfig.cs page as per our requirement but sequence matter.

Code

Controller level

It is specific for a particular controller, we can use RoutePrefixAttribute before the Controller definition as below.

    [RoutePrefix("v1/MyName/{action}")]

For calling any action name inside that controller we have to use our defined URI. In the above code we are using constant keyword as “v1” for maintaining the version and “MyName” is another constant keyword for the controller. We can give any name as per our convenience.

Action level

We can also define the action level routing as per our requirement. Suppose we have the notification service inside the same controller and we don’t want to use global or controller level routing so we can define the following:

    [Route("~/Notification/Email")]

Here, we are using tilde(~) sign for override the RoutePrefix in controller level. If we are not using controller level RoutePrefix Attribute then we can omit the tilde(~) sign.

In this way we can achieve various ways of routing technique in Web API.

Read more articles on Web API: