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.

Controllers in ASP.NET Core:

Controllers in ASP.NET Core Web API Applications play an important role in handling HTTP requests and responses. They are responsible for processing incoming HTTP requests, handling user input, retrieving and saving data, and determining the response to send back to the client.

The Controller class in ASP.NET Core Web API must have a “Controller” suffix. For example, if you want to add a controller with the name Home, then the name of the controller should be HomeController. similarly, if you want to add a controller for Student, then the name should be StudentController.

In ASP.NET Core Web API, the Controller class must be inherited from the ControllerBase class. If you are coming from an ASP.NET Core MVC background, then, in that case, the Controller class is inherited from the Controller class.

Adding Controller Class in ASP.NET Core Web API

The Controller should be added inside the Controllers folder in your project. If you have not added the Controllers folder, then please add the Controllers folder to the project root directory. Let’s add a controller with the name Employee. To do so, right-click on the Controllers folder and then select Add => Controller from the context menu, which will open the following window. From the below ‘Add Scaffold’ dialog, please select API, then API Controller – Empty, and click on the Add button as shown in the image below.

Adding Controller Class in ASP.NET Core Web API

Understanding the Different Options:

  • API Controller – Empty: This is the most basic form of an API controller in .NET 8. It typically comes without pre-defined actions and is ideal for scenarios where you want to start from scratch or when you have very specific requirements that don’t align with the pre-defined templates.
  • API Controller with Read/Write Actions: This type of controller includes basic CRUD (Create, Read, Update, Delete) operations. It’s suitable for applications where you need to manage data records, providing methods for listing, fetching, creating, updating, and deleting data.
  • API Controller with Actions using Entity Framework: This template extends the CRUD functionality by integrating Entity Framework, which is an Object-Relational Mapping (ORM) framework. It allows you to interact with your database using .NET objects, making it easier to perform data operations without writing a lot of SQL code.
  • API with Read/Write Endpoints: Similar to the API Controller with Read/Write Actions, this controller type focuses on providing endpoints for reading and writing data. It’s a more streamlined version focused on these two operations, ideal for simpler APIs where complex operations like updating or deleting are not required.
  • API Controller with Read/Write Endpoints using Entity Framework: This is a more advanced version that combines the simplicity of read/write operations with the power of Entity Framework. It’s well-suited for applications that require straightforward data access but also benefit from the efficiencies of an ORM.

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

Adding Controller Class in ASP.NET Core Web API

Once you click on the Add button, it will add the Employee Controller within the Controllers folder with the following code:

Controllers in ASP.NET Core Web API Application

Modifying the EmployeeController Class:

Let us add one action method which returns a string. So, 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";
        }
    }
}

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

Let’s add one method to the Employee Controller 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";
        }

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

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

Controllers in ASP.NET Core Web API

As shown in the above error message, the application now finds two endpoints for the incoming request and gets confused about who will serve the request, and hence, it gives the above Ambiguous Match Exception.

As per Web API standards, 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. In the Route attribute, we specified the action as part of the URI. In our upcoming articles, we will discuss Routing in detail. For 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";
        }
    }
}

With the above changes in place, now run the application. We must pass the method name as part of the URL shown in the image below.

api/employee/get

api/employee/get

api/employee/getemployee

api/employee/getemployee

Note: In this article, 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.

ApiController Attribute in ASP.NET Core Web API

The ApiController attribute in ASP.NET Core Web API is a feature introduced in ASP.NET Core 2.1 to enhance the development of HTTP-based APIs. It is applied at the class level and offers several conveniences and conventions that make building clean and well-documented Web APIs easier. Here are some key aspects of the ApiController attribute:

  • Attribute Routing Requirement: With ApiController, attribute routing becomes a requirement. This means you must use [Route], [HttpGet], [HttpPost], etc., to define the routes for your actions.
  • Automatic HTTP 400 Responses: It automatically handles model validation errors by providing a standardized response. If the request model does not satisfy the model validation rules, the API responds with a 400 Bad Request without writing additional code.
  • Binding Source Parameter: The attribute infers the source of parameters for actions. For instance, it assumes [FromBody] for complex type parameters and [FromQuery] for simple types in GET requests. This reduces the need to specify the source of the parameter explicitly.
  • Enhanced Swagger Support: When used in conjunction with tools like Swashbuckle, it provides better metadata for API documentation. This results in more descriptive Swagger UIs.
Difference Between the Controller and ControllerBase class in ASP.NET Core:

In ASP.NET Core, Controller and ControllerBase are two different base classes that can be used when building web applications. Understanding their differences is important for deciding which one to inherit from in your own controllers.

ControllerBase Class
  • Purpose: Primarily designed for building Web APIs.
  • Features: It provides access to several properties and methods useful for handling HTTP requests, such as Request, Response, ModelState, and various methods for returning data (Ok, NotFound, BadRequest, etc.). It does not include support for views or rendering HTML.
  • Use Case: Ideal for RESTful services focusing on returning data (JSON, XML) rather than rendering HTML views.
  • Namespace: Found in Microsoft.AspNetCore.Mvc.
Controller Class
  • Purpose: Designed for handling web pages, typically used in MVC applications.
  • Features: Inherits from ControllerBase. Includes all the features of ControllerBase plus additional features to support building web pages, such as returning views (View method), handling Razor views, and supporting view-specific features like ViewData and ViewBag.
  • Use Case: Best suited for applications that need to render HTML, such as traditional MVC web applications.
  • Namespace: Also found in Microsoft.AspNetCore.Mvc.
Key Differences Between ControllerBase and Controller:
View Support:
  • ControllerBase is streamlined for API development and does not support view-related features.
  • Controller extends ControllerBase with additional features for handling views, making it suitable for MVC applications where you must return HTML pages.
Intended Use:
  • ControllerBase is intended for APIs (returning data formats like JSON or XML).
  • The Controller is intended for web applications that use the MVC pattern with views.
Flexibility:
  • ControllerBase offers a lightweight and focused set of functionalities for API development.
  • The Controller provides more flexibility and features for handling both APIs and views within the same controller, but it’s heavier due to additional view-related features.
Conclusion
  • Choose ControllerBase when building a Web API or if you only need to return data formats and not views.
  • Choose Controller when building an MVC application where you need to return both data and views.
Best Practices
  • Thin Controllers: Keep business logic out of controllers and in services or other layers.
  • Use DTOs (Data Transfer Objects): Avoid exposing your database models directly; map them to DTOs.
  • Consistent Naming Convention: Follow RESTful naming conventions for actions.
  • Secure Your API: Implement authentication, authorization, and validate inputs to secure your API.
  • Unit Testing: Write unit tests for your controllers to ensure reliability and maintainability.

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 Controllers in ASP.NET Core Web API Application article.

Leave a Reply

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