Part - 8 Controllers in ASP.NET Core Web API

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Controllers in ASP.

NET Core Web API


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.

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 below image.

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.

Modifying the EmployeeController Class:


Let us add one action method which simply 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";
}
}
}

//Adding another action method


With the above changes in place, now run the application and navigates to /api/employee URL and
you should get the following exception.
As shown in the above error message, now the application finds two endpoints for the incoming
request and gets confused about who is going to serve the request, and hence it gives the above
Ambiguous Match Exception.

As per Web API standard, each resource should have a Unique Identifier. Let us do 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 session, we will discuss Routing in detail. As of now,
just 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. Now we have to pass the method name as
part of the URL as shown in the below image.

api/employee/get

api/employee/getemployee

Note: In this session, I have just given an introduction to Controllers and in our upcoming sessions,
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 it easier to build clean and well-documented Web
APIs. 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 explicitly specify the source of the
parameter.
 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:

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 need to return HTML pages.

You might also like