DEV Community

Cover image for ApiController in .NET
Shreyans Padmani
Shreyans Padmani

Posted on

ApiController in .NET

ApiController in ASP.NET Core is an attribute used for building RESTful web APIs. It enables automatic model validation, parameter binding, and standardized error responses, simplifying controller logic and improving API consistency, reliability, and developer productivity.

ApiController Attribute

The [ApiController] attribute in ASP.NET Core is used to indicate that a controller is intended to serve as an API endpoint.

It simplifies the development of RESTful APIs.

  • Attribute routing requirement
  • Automatic HTTP 400 responses
  • Binding source parameter inference
  • Problem details for error status codes

Example

Key Features of [ApiController]

1 . Attribute Routing Requirement

Applying the [ApiController] attribute enforces attribute routing. This means that actions within the controller will not be accessible via conventional routing methods (like UseEndpoints or UseMvcWithDefaultRoute). You must use the [Route] attribute on the controller or action methods.

2 .Default Bad Request Response (Problem Details)

The default response type for an HTTP 400 response is ValidationProblemDetails, which conforms to the RFC 7231 standard for problem details.

3 . Automatic HTTP 400 Responses

When model validation fails, the [ApiController] attribute automatically handles the response, returning an HTTP 400 Bad Request status.

4 . Binding Source Parameter Inference

The [ApiController] attribute automatically determines the source of certain action parameters, meaning you often don’t need to explicitly use binding attributes like [FromBody] or [FromQuery].

Conclusion

In conclusion, ApiController in ASP.NET Core streamlines API development by providing automatic validation, binding, and error handling. It reduces boilerplate code, enforces best practices, and enhances consistency, making it essential for building robust and maintainable web APIs.

Top comments (0)