Loading

ASP.NET Web API

How to Create Custom Method Names in Web API?. The Complete ASP.NET Web API Developer Course 2023 [Videos].

In this article, I am going to discuss how to create Custom Method Names in Web API applications. Please read our previous article before proceeding to this article where we discussed how to implement the CRUD Operation in ASP.NET Web API Application and we are also going to work with the same example. As part of this article, we are going to discuss the following pointers.

  1. Understanding the Default Convention used by ASP.NET Web API.
  2. Why do we need to create custom action method names in Web API?
  3. How to create Custom Method Names in ASP.NET Web API??
Understanding the Default Convention used by ASP.NET Web API.

Lets understand the default convention used by ASP.NET Web API to map HTTP verbs GET, PUT, POST, and DELETE to methods in a controller with an example. By default, the HTTP verb GET is mapped to a method in a controller that has the name Get() or starts with the word Get.

In the following EmployeesController, the method name is Get() so by default convention, this is mapped to the HTTP verb GET. Even if we rename it to GetEmployees() or GetSomething() it will still be mapped to the HTTP verb GET as long as the name of the method is prefixed with the word Get. The word Get is case-insensitive. It can be lowercase, uppercase, or a mix of both.

public class EmployeesController : ApiController
{
public HttpResponseMessage Get()
{
using (EmployeeDBContext dbContext = new EmployeeDBContext())
{
var Employees = dbContext.Employees.ToList();
return Request.CreateResponse(HttpStatusCode.OK, Employees);
}
}
}

If the method is not named as GET or if it does not start with the word GET then Web API does not know the method name to which, the GET request must be mapped and the request fails with an error message stating The requested resource does not support HTTP method "GET" with the status code 405 Method Not Allowed.

In the following example, we have renamed Get() method to LoadAllEmployees(). When we issue a GET request the request will fail because ASP.NET Web API does not know it has to map the GET request to this method.

public class EmployeesController : ApiController
{
public HttpResponseMessage LoadAllEmployees()
{
using (EmployeeDBContext dbContext = new EmployeeDBContext())
{
var Employees = dbContext.Employees.ToList();
return Request.CreateResponse(HttpStatusCode.OK, Employees);
}
}
}

To instruct Web API to map HTTP verb GET to LoadAllEmployees() method, decorate the method with [HttpGet] attribute as shown below.

public class EmployeesController : ApiController
{
[HttpGet]
public HttpResponseMessage LoadAllEmployees()
{
using (EmployeeDBContext dbContext = new EmployeeDBContext())
{
var Employees = dbContext.Employees.ToList();
return Request.CreateResponse(HttpStatusCode.OK, Employees);
}
}
}
Lets say we have the following two methods in our Employee API controller.
public class EmployeesController : ApiController
{
[HttpGet]
public HttpResponseMessage LoadAllEmployees()
{
using (EmployeeDBContext dbContext = new EmployeeDBContext())
{
var Employees = dbContext.Employees.ToList();
return Request.CreateResponse(HttpStatusCode.OK, Employees);
}
}
public HttpResponseMessage LoadEmployeeByID(int id)
{
using (EmployeeDBContext dbContext = new EmployeeDBContext())
{
var entity = dbContext.Employees.FirstOrDefault(e => e.ID == id);
if (entity != null)
{
return Request.CreateResponse(HttpStatusCode.OK, entity);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound,
"Employee with ID " + id.ToString() + "not found");
}
}
}
}

When we navigate to the URI /api/employees/1

Notice, we are getting all the Employees, instead of just the employee with Id=1. This is because in this case the GET request is mapped to LoadAllEmployees() and not to LoadEmployeeById(int id).

If you want the GET request to be mapped to LoadEmployeeById(int id) when the id parameter is specified in the URI, then decorate the LoadEmployeeById(int id) method also with the [HttpGet] attribute as shown below.

public class EmployeesController : ApiController
{
[HttpGet]
public HttpResponseMessage LoadAllEmployees()
{
using (EmployeeDBContext dbContext = new EmployeeDBContext())
{
var Employees = dbContext.Employees.ToList();
return Request.CreateResponse(HttpStatusCode.OK, Employees);
}
}
[HttpGet]
public HttpResponseMessage LoadEmployeeByID(int id)
{
using (EmployeeDBContext dbContext = new EmployeeDBContext())
{
var entity = dbContext.Employees.FirstOrDefault(e => e.ID == id);
if (entity != null)
{
return Request.CreateResponse(HttpStatusCode.OK, entity);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound,
"Employee with ID " + id.ToString() + "not found");
}
}
}
}

Thats OK. But in real-time we may have to implement multiple get or post or put methods within a single controller. For example, we have two methods as shown below

public class EmployeesController : ApiController
{
[HttpGet]
public HttpResponseMessage LoadAllEmployees()
{
using (EmployeeDBContext dbContext = new EmployeeDBContext())
{
var Employees = dbContext.Employees.ToList();
return Request.CreateResponse(HttpStatusCode.OK, Employees);
}
}
[HttpGet]
public HttpResponseMessage LoadAllMaleEmployees()
{
using (EmployeeDBContext dbContext = new EmployeeDBContext())
{
var Employees = dbContext.Employees.Where(x => x.Gender == "Male").ToList();
return Request.CreateResponse(HttpStatusCode.OK, Employees);
}
}
}

Now when we make a request with the URL /api/employees We will get the below error

Custom Methods Names in Web API

Now the question is how to access these two methods along with how we will provide a unique URL to each resource.

First, lets see the default implementation of the WebApiConfig class which is present in the App_Start Folder.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}

The default route specifies the URL route as domain Name Followed by API and controller name. In our example, it will be http://localhost:xxxxx/api/employees where “employees” is the controller name.

Implementing Custom Method Names in Web API:

To implement Custom Method Names in Web API, lets first change the default implementation of the WebApiConfig class as shown below where we include the action name as part of the route.

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Now make a request with the same URL /api/employees It will give us the following error

Custom Methods Names in WEB API

So change the URL as we need to include the action name in the URL as we do the changes in the WebApiConfig class.

/api/employees/LoadAllEmployees
/api/employees/LoadAllMaleEmployees

Thats it. We have successfully implemented Custom Method Names in Web API. Now you will get the response as expected.

See All

Comments (318 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET Web API / Blog

What is ASP.NET Web API Application?

In this ASP.NET Web API Tutorials series, I covered all the features of ASP.NET Web API. You will learn from basic to advance level features of ASP.NET Web API. The term API stands for “Application Programming Interface” and ASP.NET Web API is a framework provided by Microsoft which makes it easy to build Web APIs, i.e. it is used to develop HTTP-based web services on the top of .NET Framework.
3-Feb-2022 /34 /318

ASP.NET Web API / Blog

How to creat ASP.NET Web API Application using Visual Studio?

In this article, I am going to discuss the step-by-step procedure for Creating ASP.NET Web API Application. Please read our previous article before proceeding to this article where we gave an overview of the ASP.NET Web API framework. As part of this article, we ate going to discuss the following pointers.
3-Feb-2022 /34 /318

ASP.NET Web API / Blog

How to add Swagger in Web API Application?

In this article, I am going to discuss how to add Swagger in Web API Application to document and test restful Web API services. Please read our previous article where we discussed How to Create an ASP.NET Web API Application step by step before proceeding to this article as we are going to work with the same example. As part of this article, we are going to discuss the following pointers.
3-Feb-2022 /34 /318