Back to: ASP.NET Core Web API Tutorials
ApiController Attribute in ASP.NET Core Web API
In this article, I will explain ApiController Attribute in ASP.NET Core Web API Application with examples. Please read our previous article discussing the Dependency Injection Design Pattern in ASP.NET Core Web API Applications.
What is ApiController Attribute in ASP.NET Core Web API?
The ApiController Attribute in ASP.NET Core Web API is a specialized attribute that marks a controller as an API controller. It enhances the behavior of the controller by providing some default functionalities commonly needed in Web API applications. When we apply this attribute to a controller class, we get a lot of benefits, like model validation, automatic response formatting, and routing conventions that help streamline the development of RESTful APIs.
Why do we need the ApiController Attribute in ASP.NET Core Web API?
When we apply the [ApiController] attribute to a controller, ASP.NET Core configures several conventions and behaviors through built-in filters and conventions. Some of the key reasons to use this attribute include:
- Attribute Routing Requirement: Controllers marked with [ApiController] require attribute routing. Conventional routing (like defining routes in Program.cs) is not supported, so each action must have explicit route definitions for clarity and maintainability.
- Automatic Model State Validation: Before an action method executes, the framework automatically checks ModelState.IsValid. If the model state is invalid, it short-circuits the request and returns a 400 Bad Request response with details about the validation errors. This eliminates the need to manually check ModelState.IsValid in every action method.
- Problem Details for Error Responses: When an error occurs (like a validation failure), the framework returns a standardized error response conforming to the RFC 7807 specification called “Problem Details.” This provides a consistent structure for error information, making it easier for clients to parse and handle errors.
- Binding Source Parameter Inference: It simplifies action method signatures by inferring where parameters will likely come from depending on the context. For example, complex types are automatically inferred from the request body, while simple types are inferred from the route or query string.
Application Without ApiController
Create a new ASP.NET Core Web API project named APIControllerDemo. Then, create a folder named Models in the project root directory. Within the Models folder, add a class file named Employee.cs and copy and paste the following code:
using System.ComponentModel.DataAnnotations; namespace APIControllerDemo.Models { public class Employee { public int Id { get; set; } [Required] public string Name { get; set; } [Required] public string Position { get; set; } } }
Employee Controller
Let’s create the ProductsController without using the [ApiController] attribute. So, create a new API Empty Controller named EmployeeController within the Controllers folder and then copy and paste the following code:
using APIControllerDemo.Models; using Microsoft.AspNetCore.Mvc; namespace APIControllerDemo.Controllers { [Route("api/[controller]")] public class EmployeeController : ControllerBase { [HttpPost] public IActionResult CreateEmployee(Employee employee) { if (!ModelState.IsValid) { return BadRequest(ModelState); } // Simulate adding the employee return Ok("Employee created successfully"); } [HttpGet("{id}")] public IActionResult GetEmployee(int id) { if (id <= 0) { return BadRequest("Invalid ID provided"); } // Simulate fetching an employee return Ok(new Employee { Id = id, Name = "John Doe", Position = "Developer" }); } } }
Potential Drawbacks Without ApiController:
The following are the Potential Drawbacks Without using ApiController in ASP.NET Core Web API:
- Manual Model State Validation: Developers need to check ModelState.IsValid in every action.
- Inconsistent Error Responses: Error messages are custom-coded and may lack standardization.
- Manual Binding Source Specification: Developers need to specify where data should come from using attributes like [FromBody] or [FromQuery].
- Increased Duplicate Code: Repeated logic like model validation and error handling increases the codebase size and complexity.
Application Using ApiController
Add the [ApiController] attribute to the controller class. So, please modify the EmployeeController as follows:
using APIControllerDemo.Models; using Microsoft.AspNetCore.Mvc; namespace APIControllerDemo.Controllers { [ApiController] [Route("api/[controller]")] public class EmployeeController : ControllerBase { [HttpPost] public IActionResult CreateEmployee(Employee employee) { // Model validation is now automatic return Ok("Employee created successfully"); } [HttpGet("{id}")] public IActionResult GetEmployee(int id) { if (id <= 0) { return BadRequest("Invalid ID provided"); } // Simulate fetching an employee return Ok(new Employee { Id = id, Name = "John Doe", Position = "Developer" }); } } }
Key Improvements:
The following are the Key Improvements with ApiController Attribute:
- Automatic Model Validation: If the Employee model is invalid, the framework automatically returns a 400 Bad Request response with validation errors.
- Standardized Error Responses: Errors are formatted using the ProblemDetails standard (RFC 7807).
- Simplified Binding: Complex types like Employee are automatically bound from the request body.
- Reduced Code Duplication: No need for repetitive ModelState checks or explicit binding attributes.
Summary:
The ApiController attribute is highly recommended when building or exposing a Web API endpoint in ASP.NET Core because it streamlines development and results in a cleaner, more consistent API surface.
In the next article, I will discuss How to Create Background Service in ASP.NET Core Web API applications with Examples. Here, I explain the ApiController Attribute in the ASP.NET Core Web API application with multiple Examples. I hope you enjoy this article on “ApiController Attribute in ASP.NET Core Web API.”
Registration Open For New Online Training
Enhance Your Professional Journey with Our Upcoming Live Session. For complete information on Registration, Course Details, Syllabus, and to get the Zoom Credentials to attend the free live Demo Sessions, please click on the below links.