In Part 1 , Part 2 and Part 3 of this series, we discussed HTTP Verbs and their implementation along with Content Negotiation. Now, let’s discuss custom method names.
Custom Method Names
Now, in the Web API the user maps HTTP verbs Get, Post, Put and Delete methods in the Controller, however, in Controller, you have methods with the same name or they start with the same, like Get() is mapped to Get(), GetEmployees() or GetSomething().
Now, let’s understand with an example.
Go to File >> New Project >> select ASP.NET Web Application and add the name of the project, as shown below.
Now, select Web API as shown below.
Now, go to ValueController.
- public class ValuesController : ApiController
- {
-
- public IEnumerable<string> Get()
- {
- return new string[] { "value1", "value2" };
- }
-
-
- public string GetEmployee(int id)
- {
- return "value";
- }
-
-
- public void Post([FromBody]string value)
- {
- }
-
-
- public void Put(int id, [FromBody]string value)
- {
- }
-
-
- public void Delete(int id)
- {
- }
- }
Now, if you run the application and try to access http://localhost:XXX /api/values, then it will execute Get(); however, if you will access http://localhost:XXX /api/values/1, then it will execute GetEmployee().
Now, let's see what happens. If the name does not start with Get, so within the example, let's change the name of GetEmployee to DisplayEmployee () as shown below.
- public class ValuesController : ApiController
- {
-
- public IEnumerable<string> Get()
- {
- return new string[] { "value1", "value2" };
- }
-
-
- public string DisplayEmployee(int id)
- {
- return "value";
- }
-
-
- public void Post([FromBody]string value)
- {
- }
-
-
- public void Put(int id, [FromBody]string value)
- {
- }
-
-
- public void Delete(int id)
- {
- }
- }
Now, run the application and try to access the http://localhost:XXX /api/values/1. You will get 405 error.
Since the Web API is not able to understand DisplayEmployee(), we can instruct it by decorating HttpGet attribute.
Now, add [HttpGet] attribute to DisplayEmployee() as shown below.
- public class ValuesController : ApiController
- {
-
- public IEnumerable<string> Get()
- {
- return new string[] { "value1", "value2" };
- }
-
-
- [HttpGet]
- public string DisplayEmployee(int id)
- {
- return "value";
- }
-
-
- public void Post([FromBody]string value)
- {
- }
-
-
- public void Put(int id, [FromBody]string value)
- {
- }
-
-
- public void Delete(int id)
- {
- }
- }
Now, run the application and try to access http://localhost:XXX /api/values/1
Similarly, you can use [HttpPost], [HttpPut] and [HttpDelete].
In the next article, we will be discussing how to call WebAPI using jQuery.