.NET › Global Exception Handling & Middleware
What is the role of the [ApiController] attribute in automatically handling certain error scenarios without explicit exception handling code?
IntermediateAnswer
[ApiController] enables several automatic API-friendly behaviors beyond just validation: automatic 400 responses for invalid model state, automatic binding source inference, and automatic problem details for certain error responses -- reducing boilerplate that would otherwise require manual exception handling or explicit checks in every action for common scenarios like malformed request bodies or missing required parameters.
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase {
[HttpPost]
public IActionResult Create(ProductDto dto) {
// No need to manually check ModelState.IsValid --
// [ApiController] already returned 400 automatically if dto was invalid
return Ok(_service.Create(dto));
}
}Real-world example A team migrating older MVC controllers (which required manual `if (!ModelState.IsValid) return BadRequest(ModelState);` checks in every action) to use [ApiController] removes dozens of duplicated validation-checking lines across their controllers.