Introduction
In the previous lessons, we created the solution structure, separated the application layers, defined domain models and data contracts, introduced repositories and Unit of Work, implemented business services, and configured dependency injection. This lesson focuses on the application boundary that communicates with external clients: the ASP.NET Core REST API.
The goal is not to move database code into controllers. Instead, controllers should translate HTTP requests into calls to the business layer and translate business results into consistent HTTP responses. We will use a Product resource to implement endpoints for listing products, retrieving a single product, creating a product, updating a product, and deleting a product.
The examples use controller-based ASP.NET Core Web API patterns compatible with .NET 8 and later. Namespaces or project templates can vary between versions, but the REST and controller design principles remain the same.
REST and resource-oriented design
REST is an architectural style that uses the standard capabilities of HTTP to work with resources. A resource represents a meaningful entity in the application. In this example, the resource collection is products. Resource URLs generally use nouns rather than action verbs:
GET /api/products: Retrieve the product collection.GET /api/products/5: Retrieve the product whose identifier is 5.POST /api/products: Create a new product.PUT /api/products/5: Replace product 5.PATCH /api/products/5: Partially modify product 5.DELETE /api/products/5: Delete product 5.
A path such as /api/getProducts can work technically, but resource-oriented URLs are easier to understand and predict. The HTTP method expresses the operation instead of adding a verb to the URL.
Meaning of HTTP methods
| Method | Typical purpose | Common success response |
|---|---|---|
GET | Read a resource | 200 OK |
POST | Create a resource | 201 Created |
PUT | Replace a resource completely | 200 OK or 204 No Content |
PATCH | Modify selected fields | 200 OK or 204 No Content |
DELETE | Delete a resource | 204 No Content |
Idempotency is another important concept. Repeating the same PUT or DELETE request should not continue changing the result after the first successful operation. POST is generally not idempotent because sending the same request repeatedly may create multiple resources.
Controller responsibilities
In ASP.NET Core, a controller is a class that receives HTTP requests and produces responses through action methods. A well-designed controller typically has these responsibilities:
- Map the request URL and HTTP method to the correct action.
- Receive values from route segments, query strings, and request bodies.
- Use model binding and validation results.
- Call a business service through dependency injection.
- Select an appropriate HTTP status code and response body.
A controller should not write SQL, construct repositories, calculate complex business values, or contain the entire application rule set. Those responsibilities belong in the appropriate lower layers. Keeping controllers thin improves readability, testing, and long-term maintenance.
Preparing the API project
The API project must register controllers and map controller endpoints in Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Service registrations introduced in the previous lesson
builder.Services.AddScoped<IProductService, ProductService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapControllers();
app.Run();AddControllers registers the controller-based MVC services. MapControllers adds attribute-routed controller actions to the endpoint map. If either call is missing, controller endpoints may not behave as expected.
Designing the first ProductsController
We will derive the controller from ControllerBase and use [ApiController] and [Route]. The [ApiController] attribute enables API-specific behavior, including improved parameter binding and automatic 400 responses when model validation fails.
using Microsoft.AspNetCore.Mvc;
namespace Catalog.Api.Controllers;
[ApiController]
[Route("api/[controller]")]
public sealed class ProductsController : ControllerBase
{
private readonly IProductService _productService;
public ProductsController(IProductService productService)
{
_productService = productService;
}
[HttpGet]
public async Task > GetAll(
CancellationToken cancellationToken)
{
var products = await _productService.GetAllAsync(cancellationToken);
return Ok(products);
}
[HttpGet("{id:int}")]
public async Task GetById(
int id,
CancellationToken cancellationToken)
{
var product = await _productService.GetByIdAsync(id, cancellationToken);
if (product is null)
{
return NotFound();
}
return Ok(product);
}
} In [Route("api/[controller]")], the [controller] token removes the Controller suffix from the class name, producing the products segment. The base route therefore becomes /api/products. The action attribute [HttpGet("{id:int}")] maps only URLs whose id segment can be parsed as an integer.
Using route constraints
The {id:int} constraint prevents a request such as /api/products/abc from matching this action. Constraints reduce ambiguous route matches. They are not a replacement for complete validation: whether a product actually exists must still be checked by the business or data access layer.
Create, update, and delete actions
When creating a product, accept a request DTO, pass it to the service, and return 201 Created after a successful operation. CreatedAtAction can generate the URL of the new resource and place it in the Location response header:
[HttpPost]
public async Task Create(
CreateProductRequest request,
CancellationToken cancellationToken)
{
var created = await _productService.CreateAsync(request, cancellationToken);
return CreatedAtAction(
nameof(GetById),
new { id = created.Id },
created);
}
[HttpPut("{id:int}")]
public async Task Update(
int id,
UpdateProductRequest request,
CancellationToken cancellationToken)
{
var updated = await _productService.UpdateAsync(
id,
request,
cancellationToken);
if (!updated)
{
return NotFound();
}
return NoContent();
}
[HttpDelete("{id:int}")]
public async Task Delete(
int id,
CancellationToken cancellationToken)
{
var deleted = await _productService.DeleteAsync(id, cancellationToken);
return deleted ? NoContent() : NotFound();
} The controller does not know how the product is stored. Creation, update, deletion, and related rules are delegated to IProductService. If an update or delete target does not exist, the endpoint returns 404 Not Found. When a successful operation has no response body, 204 No Content is appropriate.
Binding route, query, and body values
ASP.NET Core can bind action parameters from different parts of an HTTP request. Use [FromRoute] for route values, [FromQuery] for query string values, and [FromBody] for a JSON request body. With [ApiController], many binding sources are inferred automatically, but explicit attributes can make intent clearer.
[HttpGet]
public async Task<ActionResult<IReadOnlyList<ProductDto>>> Search(
[FromQuery] string? search,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 20,
CancellationToken cancellationToken = default)
{
if (page < 1 || pageSize is < 1 or > 100)
{
return BadRequest("page must be at least 1 and pageSize must be between 1 and 100.");
}
var result = await _productService.SearchAsync(
search,
page,
pageSize,
cancellationToken);
return Ok(result);
}An example request is GET /api/products?search=keyboard&page=1&pageSize=10. Pagination, filtering, and sorting options belong naturally in the query string. This keeps the resource path stable instead of creating a separate verb-based endpoint for every variation.
Status codes and action return types
An API response is more than a JSON body. The HTTP status code communicates the outcome to the client. Common status codes include:
200 OK: A successful read or a successful operation with a response body.201 Created: A new resource was created.204 No Content: The operation succeeded and has no response body.400 Bad Request: The request format or values are invalid.404 Not Found: The requested resource does not exist.409 Conflict: The operation conflicts with the current resource state.500 Internal Server Error: An unexpected server failure occurred.
ActionResult<T> is useful when an action normally returns a DTO but may also return NotFound or BadRequest. The [ProducesResponseType] attribute documents possible results and improves the generated Swagger/OpenAPI metadata:
[HttpGet("{id:int}")]
[ProducesResponseType(typeof(ProductDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<ProductDto>> GetById(
int id,
CancellationToken cancellationToken)
{
var product = await _productService.GetByIdAsync(id, cancellationToken);
return product is null ? NotFound() : Ok(product);
}Common mistakes
- Using DbContext directly in the controller: This moves data access and business responsibilities into the API layer. Depend on the application service instead.
- Returning entities directly: Internal fields may be exposed and circular reference problems may occur. Use response DTOs.
- Returning 200 for every result: Use 404 for missing resources, 201 for creation, and 204 for successful deletion without a body.
- Putting verbs in resource routes: Prefer
DELETE /api/products/5over/api/products/delete/5. - Ignoring cancellation: Pass
CancellationTokenfrom the action through the service and repository layers. - Mixing DTO validation and business validation: Required fields belong in request validation; uniqueness, stock, and workflow rules belong in the business layer.
- Creating ambiguous routes: Similar templates and HTTP methods can cause action-selection conflicts. Use constraints and explicit route design.
Short practice exercise
Task: Add category filtering and product creation support to the API.
- Create an action for
GET /api/products?categoryId=2. - Read
categoryIdwith[FromQuery]. - Delegate filtering to
IProductService.SearchAsyncrather than implementing it in the controller. - Create a
CreateProductRequestDTO and make the product name required. - Return
201 Createdafter a successful creation,400 Bad Requestfor invalid input, and an appropriate business result for a duplicate-name rule violation. - Use Swagger or Postman to test successful, missing-resource, and invalid-request scenarios.
Check your design: someone reading the controller should understand the endpoint behavior without knowing how SQL Server stores the product.
Conclusion
This lesson introduced resource-oriented REST design, the roles of HTTP methods, attribute routing, route constraints, controller responsibilities, and status code selection. The ProductsController acts as a thin adapter between the HTTP layer and the business service. This makes the layered structure from the previous lessons usable through real API endpoints.
In the next stages, the web application will call these endpoints, error responses will be standardized, and validation and API documentation will be expanded. A strong API is not defined by the number of endpoints it contains. It is defined by clear resources, correct HTTP behavior, predictable responses, and focused responsibilities.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/actions?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-10.0