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
- {
- // GET api/values
- public IEnumerable<string> Get()
- {
- return new string[] { "value1", "value2" };
- }
- // GET api/values/5
- public string GetEmployee(int id)
- {
- return "value";
- }
- // POST api/values
- public void Post([FromBody]string value)
- {
- }
- // PUT api/values/5
- public void Put(int id, [FromBody]string value)
- {
- }
- // DELETE api/values/5
- 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
- {
- // GET api/values
- public IEnumerable<string> Get()
- {
- return new string[] { "value1", "value2" };
- }
- // GET api/values/5
- public string DisplayEmployee(int id)
- {
- return "value";
- }
- // POST api/values
- public void Post([FromBody]string value)
- {
- }
- // PUT api/values/5
- public void Put(int id, [FromBody]string value)
- {
- }
- // DELETE api/values/5
- 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
- {
- // GET api/values
- public IEnumerable<string> Get()
- {
- return new string[] { "value1", "value2" };
- }
- // GET api/values/5
- [HttpGet]
- public string DisplayEmployee(int id)
- {
- return "value";
- }
- // POST api/values
- public void Post([FromBody]string value)
- {
- }
- // PUT api/values/5
- public void Put(int id, [FromBody]string value)
- {
- }
- // DELETE api/values/5
- 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].

Join the conversation! Your thoughts help the community grow.