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.
The following are some prerequisites before you proceed any further in this article:
Prerequisites:
The prerequisites include knowledge about the following technologies:
- ASP.NET MVC 5.
- C# programming.
- REST Web API.
You can download complete source code from here or you can follow step by step discussion below. The sample code is developed in Microsoft Visual Studio 2013 Ultimate.
Let's begin now:
- Create new Web API project and name it "WebApiRouting".
- Rename "ValueController.cs" file to "WebApiController.cs".
- 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:
-
- [Route("api/WebApi/GetValById")]
- [HttpGet]
- public string GetValById(int studentId)
- {
- return "Hello Student Id = " + studentId;
- }
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:
Route("api/WebApi/GetValById")]
- Now, execute the project and use following link in the browser to see your newly created REST Web API method in action as follows:
yourlink:port/api/WebApi/GetValById?StudentId=8
Conclusion
In this tutorial you will learn how to use REST Web API routing to create new method of same argument type with different name. You will also learn how to access Rest Web API routing method.
Read more articles on ASP.NET: