Clean Code in ASP.NET Core: How to Write Clean and Maintainable REST APIs


REST APIs are now at the heart of many modern applications. Writing clean, clear, and easily maintainable APIs is essential to ensure scalability, ease of development, and a reliable user experience.
In this article, we will look at best practices to create REST APIs in ASP.NET Core that follow clean code principles.
Organize the project well
A clear structure helps maintain order and facilitates collaboration.
Tips:
Divide the project into folders/logical layers such as Controllers, Services, Repositories, Models, DTOs.
Keep business logic out of the controllers.
Use consistent and meaningful naming (e.g., OrderController, IOrderService, OrderDto).
Keep controllers slim and focused
Controllers should orchestrate calls to services and return responses, not contain complex logic.
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
private readonly IOrderService _orderService;
public OrdersController(IOrderService orderService)
{
_orderService = orderService;
}
[HttpGet("{id}")]
public IActionResult GetOrder(int id)
{
var order = _orderService.GetOrderById(id);
if (order == null) return NotFound();
return Ok(order);
}
}
Use DTOs for input/output
Do not expose database entities directly.
DTOs (Data Transfer Objects) allow separating the domain model from the API contracts.
public class OrderDto
{
public int Id { get; set; }
public string CustomerName { get; set; }
// other necessary fields
}
Validation handling
Data Annotations
public class CreateOrderDto
{
[Required]
public string CustomerName { get; set; }
[Range(1, int.MaxValue)]
public int Quantity { get; set; }
}
ASP.NET Core automatically validates models when using [ApiController]
.
FluentValidation (optional)
Use for more complex validations or business rules.
Error handling and consistent responses
Use appropriate HTTP status codes (200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Internal Server Error).
Return clear and consistent error messages.
Centralize error handling using middleware (e.g.,
UseExceptionHandler
).
Logging and monitoring
Integrate logging with ILogger<T>
to track important events and facilitate debugging.
API testing
Write automated tests for controllers and services.
Use tools like Postman or Swagger for manual testing and documentation.
Conclusion
Following these best practices helps you create REST APIs in ASP.NET Core that are clean, maintainable, and scalable, respecting clean code principles and a solid architecture.
Subscribe to my newsletter
Read articles from Developer Fabio directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Developer Fabio
Developer Fabio
I'm a fullstack developer and my stack is includes .net, angular, reactjs, mondodb and mssql I currently work in a little tourism company, I'm not only a developer but I manage a team and customers. I love learning new things and I like the continuous comparison with other people on ideas.