Controllers in ASP.NET Core Web API

Controllers in ASP.NET Core Web API

In this article, I will discuss Controllers in ASP.NET Core Web API Application. Please read our previous article discussing How to Install and Use Swagger API in the ASP.NET Core Web API.

What are Controllers in ASP.NET Core Web API?

Controllers are fundamental components in ASP.NET Core Web API applications. They are classes responsible for handling incoming HTTP requests, processing them, and generating appropriate HTTP responses. They act as an intermediary between the client and the server, responsible for processing requests, executing business logic, and returning data in formats such as JSON or XML. Controllers typically manage the flow of data between the client and server and adhere to REST principles.

The following are the Key Roles of a Controller:

  • Request Handling: Controllers receive HTTP requests and route them to the appropriate action methods. Each action method within a controller generally corresponds to a specific type of HTTP request (e.g., GET, POST, PUT, or DELETE).
  • Data Processing: Controllers interact with models and services to process data, implement business logic, and perform operations such as querying a database to perform database CRUD Operations, applying business rules and validations, or transforming data for the client.
  • Response Generation: Based on the outcome of the processing, controllers generate HTTP responses which will return to the client. These responses can include data payloads (e.g., JSON, XML, etc.), status codes (e.g., 200 OK, 404 Not Found, 400 Bad Request, etc.), and error messages.
Adding Controller Class in ASP.NET Core Web API

When creating a controller in an ASP.NET Core Web API project, adhere to the following conventions and best practices:

Naming Convention:

By convention, ASP.NET Core recognizes controller classes whose names end with the “Controller” suffix. So, the controller class name must have the “Controller” suffix. For example:

  • A controller for managing employees should be named EmployeeController.
  • A controller for handling students should be named StudentController.
Base Class:

Controllers in ASP.NET Core Web API typically inherit from the ControllerBase class, which provides essential methods and properties for handling HTTP requests and generating responses without the overhead of view support. If server-side rendering of views is needed, use the Controller class instead of the ControllerBase class. The Controller class is inherited from the ControllerBase class.

Recommended Folder Structure:

Controllers should be placed in your project’s Controllers folder. If the folder does not exist, create it in the root directory to maintain a clean and organized project structure.

Steps to Add a Controller:

Let’s add a controller with the name Employee. To do so, right-click on the Controllers folder and select Add => Controller from the context menu, which will open the following window. From the Add New Scaffold Item, please choose APIthen API Controller – Empty, and click the Add button, as shown in the image below.

Adding Controller Class in ASP.NET Core Web API

Understanding the Different Options:

Let us understand the different options for creating an API Controller in ASP.NET Core:

API Controller – Empty

This template creates a basic API controller class without any predefined actions. It’s suitable when you want full control over defining your own actions and endpoints. We need to use this template when we prefer to manually define all CRUD operations and their corresponding HTTP verbs (GET, POST, PUT, DELETE). It starts with an empty controller class that we need to populate with our desired actions.

API Controller with Read/Write Actions

This template generates basic CRUD actions (e.g., Get, Post, Put, Delete). You need to use this template when you want to quickly set up a standard RESTful controller without custom logic. It sets up actions for listing all resources, retrieving a resource by ID, creating a new resource, updating an existing resource, and deleting a resource.

API Controller with Actions Using Entity Framework

This template extends the “API Controller with Read/Write Actions” template by integrating Entity Framework Core for database interactions. You need to use this template when your controller directly interacts with a database to perform basic CRUD operations on entities.

API with Read/Write Endpoints

Similar to the “API Controller with Read/Write Actions” template, but it allows more flexibility for customizing endpoint names and HTTP verbs. You need to use this template when you need more control over endpoint naming or want to include additional actions beyond basic CRUD operations.

API Controller with Read/Write Endpoints Using Entity Framework

Combines database integration with customizable endpoint names. You need to use this template when you need both database integration (via EF Core) and custom endpoint naming.

Note: For initial learning and setup, select API Controller – Empty to understand the fundamentals before exploring more advanced templates.

Selecting API Controller – Empty

So, please select API Controller – Empty and click on the Add button. This will open the following Add New Item window. Here, you need to give the controller the name EmployeeController and then click on the Add button, as shown in the image below.

Controllers in ASP.NET Core Web API

Once you click the Add button, the Employee Controller will be added to the Controllers folder with the following code. As you can see, the Employee Controller was created without any additional logic. I mean, there are no actions defined within the Controller, and this is because we choose API Controller – Empty when we create the controller.

 Controllers in ASP.NET Core Web API Application

Modifying the EmployeeController Class:

Add one action method within the Employee Controller to return a simple string. So, please modify the EmployeeController class as shown in the below code.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace MyFirstWebAPIProject.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            return "Returning from EmployeeController Get Method";
        }
    }
}
Code Explanation:
  • [Route(“api/[controller]”)]: Sets the base route for the controller, where [controller] is a placeholder for the controller name (employee in this case).
  • [ApiController]: Enables API-specific behaviors and features. Indicates that this controller is intended for Web API. This attribute enforces attribute routing and automatically handles model validation, among other things.
  • Get Method: Handles HTTP GET requests to api/employee.

With the above changes in place, now run the application and navigate to /api/employee URL, and you should see the following result.

Modifying the EmployeeController Class

Adding Another Action Method:

Let’s add another action method into the Employee Controller class as follows. Now, the controller has two action methods, and both action methods are decorated with the HttpGet attribute, meaning they can respond to GET HTTP Requests only.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace MyFirstWebAPIProject.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            return "Returning from EmployeeController Get Method";
        }

        [HttpGet]
        public string GetEmployee()
        {
            return "Returning from EmployeeController GetEmployee Method";
        }
    }
}

With the above changes, now run the application and navigate to /api/employee URL, and you will get the following exception.

Ambiguous Match Exception in ASP.NET Core Web API

Why Do We Get Exception?

As shown in the above error message, the application now finds two endpoints for the incoming HTTP request and gets confused about who will serve the request. Hence, it gives the above Ambiguous Match Exception. This occurs because both Get and GetEmployee methods are mapped to the same HTTP GET route (api/employee), causing ambiguity.

Resolving Route Ambiguity:

As per Restful Service, each resource should have a Unique Identifier. Let us make some changes in our Route Attribute so that each request will have a unique URI. Modify the routing to include action names, ensuring each endpoint has a unique URI. To do so, we specified the action as part of the URI. In our upcoming session, we will discuss Routing in detail. As of now, modify the EmployeeController class as shown below.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace MyFirstWebAPIProject.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            return "Returning from EmployeeController Get Method";
        }

        [HttpGet]
        public string GetEmployee()
        {
            return "Returning from EmployeeController GetEmployee Method";
        }
    }
}
Code Explanation:

[Route(“api/[controller]/[action]”)]: Incorporates the action method name into the route, ensuring each action has a distinct endpoint.

  • api/employee/get → Invokes the Get method.
  • api/employee/getemployee → Invokes the GetEmployee method.

With the above changes, now run the application. Now we have to pass the method name as part of the URL as shown in the below image.

api/employee/get

What are Controllers in ASP.NET Core Web API?

api/employee/getemployee

Controllers in ASP.NET Core Web API Application with Examples

Note: Here, I have just given an introduction to Controllers, and in our upcoming articles, we will discuss how to implement GET, POST, PUT, PATCH, and DELETE Methods in a proper manner.

Difference Between the Controller and ControllerBase class in ASP.NET Core:

In ASP.NET Core, both Controller and ControllerBase classes serve as base classes for controllers, but they are designed for different scenarios and provide different sets of functionalities and features.

ControllerBase Class in ASP.NET Core

It serves as a lightweight base class for Web API controllers that do not require view support. The following are some of the Key Features of ControllerBase Class:

  • Core MVC Features: Provides access to essential functionalities like action methods, routing, model binding, and HTTP context manipulation.
  • No View Support: This does not include support for rendering views (e.g., HTML or Razor views), making it ideal for APIs that solely return data.
  • Helper Methods: Offers various helper methods such as Ok(), NotFound(), BadRequest(), etc., to facilitate standard HTTP responses.
  • Lightweight: Eliminates the overhead associated with view rendering, resulting in better performance for API endpoints.
  • Use Case: Building RESTful APIs that return data in formats like JSON or XML without needing server-side rendered views.
Controller Class in ASP.NET Core

It extends the ControllerBase class by adding support for view-related functionalities, making it suitable for MVC applications that render server-side views. It supports all the features ControllerBase Class supports and additional features designed explicitly for MVC applications. The following are some of the Key Features of the Controller Class:

  • All ControllerBase class Features: Inherits all core functionalities provided by ControllerBase.
  • View Support: Includes methods and properties for rendering views, such as View(), PartialView(), and access to ViewBag and ViewData.
  • Additional Functionality: Provides capabilities related to managing and rendering HTML views using Razor syntax.
  • Use Case: Developing traditional MVC applications where controllers handle both data endpoints and server-side view rendering.

For a better understanding, please look at the following image:

Difference Between the Controller and ControllerBase class in ASP.NET Core

Choosing Between Controller and ControllerBase in ASP.NET Core

When deciding which base class to inherit from, consider the primary responsibilities of your controller:

Use ControllerBase When:
  • Building a Web API focused solely on handling HTTP requests and returning data.
  • You do not need to support or render server-side views.
  • Aim to keep the project lightweight and optimized for data-driven endpoints.
Use Controller When:
  • Developing an MVC application that requires server-side rendering of views.
  • Your controller needs to handle both data operations and view rendering.
  • Using view-related features like ViewBag, ViewData, and Razor views is necessary.
  • For a better understanding, please look at the following image:

For a better understanding, please look at the following image:

Choosing Between Controller and ControllerBase in ASP.NET Core

Controllers are the heart of ASP.NET Core Web APIs, handling HTTP requests, executing business logic, and generating responses. Proper routing, action methods, and using [ApiController] enhance API functionality, maintainability, and performance.

In the next article, I will discuss Models in ASP.NET Core Web API Application. In this article, I try to explain Controllers in ASP.NET Core Web API Application. I hope you enjoy this article about Controllers in ASP.NET Core Web API Applications.

4 thoughts on “Controllers in ASP.NET Core Web API”

  1. Anurag Singh Parihar

    Hi
    Can you please give next button at every page of the end so that we need not to scroll up and then we go to next page

    1. Anurag singh parihar,
      We are on the same page; I would like to request the next button at the end of every pages, It is more userfriendly.

  2. This website is really very helpful for Dotnet Developers who want to learn the technology. It is presented in very good manner. Thank you sir for providing this in-depth explanation.

Leave a Reply

Your email address will not be published. Required fields are marked *