REST Web API is the most common and vital part of data accessibility via any platform that does have access to database directly. Web API development with Microsoft technologies are a piece of cake thanks to the default scaffolding. There is however, one aspect in web API that sometimes becomes necessary to achieve. In Microsoft web API technologies the frame work understand all the basic GET, POST, PUT, DELETE methods implementation with the same name as method type with alteration of arguments. But, at times there comes a situation when we need a method of similar type with same arguments but different name for different purpose, such scenario can be easily achieved by using REST Web API routing.
Today, I shall demonstrate a simple GET type method with different name and same argument type by using REST Web API routing.
Following are few prerequisites before you proceed any further:
You can download complete source code or you can follow step by step discussion below. The sample code is developed in Microsoft Visual Studio 2013 Ultimate.
Let’s begin now:
1) Create new Web API project and name it “WebApiRouting“.
2) Rename “ValueController.cs” file to “WebApiController.cs“.
3) You will see default scaffold REST Web API functions, notice that on GET method has passing parameter of type int, Let say I have a scenario in which I need another method with same number of parameters and parameter type as default GET method. In common sense one must declare a new method with different name and same parameter, but, when you try to execute the code, an exception will occur stating that similar method exist this is because REST Web API framework is design in such way that it only accept default method we are only allow to vary the argument. But, the framework provides a mechanism called routing to achieve such scenario. Now, in “WebApiController.cs” file create a new method as shown in the snippet:
In above method I simple create a new method GET type method with different name and following attribute is important because this will notify the framework that we are using GET type method with same type of parameter but, with different name:
4) Now, execute the project and use following link in the browser to see your newly created REST Web API method in action as follow:
That’s about it.