Nowadays Web API is a popular framework in .NET because of its lightweight 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:
- Global level
- Controller level
- Action 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.
As shown in the image we can change the routeTemplate value as per our requirement.
If we want to route with action name then we have to change our routeTemplate as below:
In the above code, our URI is changed as:
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.
It is specific for a particular controller, we can use RoutePrefixAttribute before the Controller definition as below.
For calling any action name inside that controller we have to use our defined URI. In the above code, we are using the 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.
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:
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.