LESSON 14 OF 22

Designing ASP.NET Core API Controllers and REST Endpoints

Learn how to create API-layer controllers, use DTOs in endpoints, design RESTful routes, and return appropriate HTTP methods and status codes in a Clean Architecture application.

35 dk 77

Introduction

In the previous lesson, we configured dependencies between the application layers using Dependency Injection. We can now expose the use cases and application services from the Application layer to external clients. Controllers in the Presentation or API layer provide this entry point.

The primary responsibility of a controller is not to implement business rules. A controller receives an HTTP request, interprets routes and parameters, binds input to a request DTO, invokes an application service, and converts the result into a meaningful HTTP response. For this reason, controllers should remain thin.

In this lesson, we will use a product-management scenario. We assume that the Application layer already contains abstractions such as IProductService, CreateProductRequest, ProductResponse, and ProductListResponse.

The Controller’s Place in Clean Architecture

The API layer is the application’s entry point for the outside world. HTTP, JSON, routing, authorization attributes, and Swagger/OpenAPI details can live here. The Domain layer, however, should not know about ASP.NET Core or HTTP status codes.

LayerResponsibility
DomainEntities, value objects, and business rules
ApplicationUse cases, DTOs, service contracts, and application workflows
InfrastructureEF Core, repositories, and external-system implementations
API/PresentationHTTP endpoints, controllers, routes, and response mapping

A controller should not use DbContext or a repository directly. It should depend on an application service abstraction. This keeps the API layer independent from the persistence technology and makes controller tests easier to write.

Creating the Controller

Web API controllers commonly derive from ControllerBase. The Controller class also includes MVC view support, so ControllerBase is the more focused choice for JSON-based APIs.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Application.Products;

namespace Api.Controllers;

[ApiController]
[Route("api/products")]
public sealed class ProductsController : ControllerBase
{
    private readonly IProductService _productService;

    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }
}

The [ApiController] attribute enables API-specific behavior, including automatic model-binding and model-validation responses. The [Route] attribute defines the base URL template for the controller’s actions.

A fixed route such as api/products provides a readable and stable public address. You may also use [Route("api/[controller]")], but some teams prefer not to make the public API contract depend directly on a controller class name.

GET Endpoints and DTOs

Use the HTTP GET method for retrieval. Since a GET request should not modify server state, it is designed to be safe and idempotent.

[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task GetAll(
    [FromQuery] ProductQueryParameters parameters,
    CancellationToken cancellationToken)
{
    var result = await _productService.GetAllAsync(parameters, cancellationToken);
    return Ok(result);
}

[FromQuery] binds pagination, search, and sorting values from the query string. For example: GET /api/products?pageNumber=2&pageSize=20&search=keyboard. The controller should not build the LINQ query itself; it should pass the parameters to the application service.

Returning a DTO such as ProductListResponse is safer than returning a domain entity. DTOs prevent database-specific fields from leaking into the public contract, keep response shapes independent from domain models, and make future API changes more controlled.

Retrieving a single resource

[HttpGet("{id:int}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task GetById(
    int id,
    CancellationToken cancellationToken)
{
    var product = await _productService.GetByIdAsync(id, cancellationToken);

    if (product is null)
    {
        return NotFound();
    }

    return Ok(product);
}

The {id:int} route constraint ensures that only integer values are selected for this action. Invalid route values do not need to travel into the action. When a resource does not exist, 404 Not Found tells the client that the request shape was valid but the requested resource could not be found.

Designing POST, PUT, and DELETE

Use POST to create a new resource. The request body should be represented by a request DTO.

[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task Create(
    [FromBody] CreateProductRequest request,
    CancellationToken cancellationToken)
{
    var product = await _productService.CreateAsync(request, cancellationToken);

    return CreatedAtAction(
        nameof(GetById),
        new { id = product.Id },
        product);
}

CreatedAtAction reports that a resource was created with the 201 Created status code and generates a Location header pointing to the endpoint that can retrieve the new resource. This communicates more information than returning 200 OK for every successful operation.

Use PUT when the client replaces or updates the complete representation of a resource:

[HttpPut("{id:int}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task Update(
    int id,
    [FromBody] UpdateProductRequest request,
    CancellationToken cancellationToken)
{
    var updated = await _productService.UpdateAsync(id, request, cancellationToken);

    if (!updated)
    {
        return NotFound();
    }

    return NoContent();
}

If the operation succeeds and the response does not contain a body, 204 No Content is appropriate. If the API returns the updated resource, use 200 OK together with a response DTO.

Use DELETE to remove a resource:

[HttpDelete("{id:int}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task Delete(
    int id,
    CancellationToken cancellationToken)
{
    var deleted = await _productService.DeleteAsync(id, cancellationToken);

    if (!deleted)
    {
        return NotFound();
    }

    return NoContent();
}

HTTP Methods and Status Codes

Status codeTypical use
200 OKThe request succeeded and a response body is available.
201 CreatedA new resource was created.
204 No ContentThe operation succeeded without a response body.
400 Bad RequestThe request format or values are invalid.
404 Not FoundThe requested resource does not exist.
409 ConflictThe request conflicts with the current resource state.
500 Internal Server ErrorAn unexpected server-side failure occurred.

Do not confuse client errors with server errors. For example, if a product code is already in use, the application service can report a conflict and the API layer can return 409. Instead of placing a broad try-catch block in every action, use centralized exception-handling middleware for unexpected failures.

Model Binding and Validation

Request DTOs explicitly define the data expected by an endpoint. When FluentValidation is used, validation rules can remain in the Application layer. The API layer then exposes validation results as HTTP responses.

public sealed record CreateProductRequest(
    string Name,
    decimal Price,
    int CategoryId);

With [ApiController], invalid model state can automatically produce a 400 Bad Request response. Business-rule violations are different from technical input validation. For example, adding a product to a category that does not exist is an application-level rule and should be handled by the Application layer.

Swagger and Response Contracts

[ProducesResponseType] attributes describe possible status codes and response types to Swagger/OpenAPI tooling. This helps client developers understand endpoint behavior from the documented contract instead of guessing from implementation details.

Ensure that controller mapping is enabled in the application startup configuration:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();
app.MapControllers();

app.Run();

Common Mistakes

  • Using EF Core inside controllers: This couples the API layer to Infrastructure and mixes responsibilities.
  • Returning entities directly: This may expose unnecessary fields and create serialization cycles.
  • Returning 200 for every successful operation: The semantic difference between creation, deletion, and update is lost.
  • Designing ambiguous routes: Prefer resource-oriented routes over verb-oriented addresses such as /api/products/action.
  • Implementing business rules in controllers: The same rules will likely be duplicated at other entry points.
  • Ignoring CancellationToken: Database operations may continue consuming resources after an HTTP request has been cancelled.

Practice Exercise

Create a CategoriesController in the existing project. Design the following endpoints:

  1. Return a category collection with GET /api/categories.
  2. Return one category with GET /api/categories/{id}.
  3. Create a category with POST /api/categories and return 201 Created.
  4. Delete a category with DELETE /api/categories/{id} and return 204 No Content on success.
  5. Document at least two possible HTTP status codes for every action.

After completing the exercise, send valid and invalid requests through Swagger UI. Verify that a missing id produces 404, missing required input produces 400, and a successful creation produces 201.

Conclusion

In this lesson, we created controllers that expose Application services through HTTP. We saw how DTOs protect boundaries, why routes should be designed around resources, and how selecting the correct HTTP method and status code improves API quality.

A well-designed controller is short, readable, and focused on coordinating application services. Data access, complex business rules, and external-system details remain outside the controller. In the next step, we will make validation and centralized exception handling more systematic so that our endpoints become more predictable and reliable.

Official references: ASP.NET Core Web API and Controller action return types.

Sources