Controllers
Action results, action filters and constructor DI.
Controllers in ASP.NET Core
1. About
Prerequisites
- Basic C# syntax, classes, interfaces, and dependency injection.
- Understanding of HTTP methods and status codes.
- Familiarity with the middleware pipeline and routing in ASP.NET Core.
- Basic knowledge of DTOs and REST API concepts.
Learning outcomes
After completing this module, you will be able to:
- Explain the role of controllers in ASP.NET Core MVC and Web APIs.
- Distinguish
Controller,ControllerBase, and Minimal API handlers. - Create controllers and action methods using attribute routing.
- Understand model binding, model validation, DTOs, and
[ApiController]. - Return appropriate status codes and response types.
- Use constructor injection to access application services.
- Understand filters and where they fit in the request pipeline.
- Design controllers that are testable, secure, maintainable, and production-ready.
- Diagnose common controller issues and answer interview questions confidently.
2. Introduction
What is a controller?
A controller is a class that groups related HTTP request-handling actions. In an ASP.NET Core web application, routing selects an appropriate action, the controller coordinates the work needed to handle the request, and the action returns a result that ASP.NET Core turns into an HTTP response.
For example, an e-commerce application might have a ProductsController with actions to list products, retrieve one product, create a product, update a product, and delete a product.
[ApiController]
[Route("api/products")]
public sealed class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetAll() =>
Ok(new[] { "Keyboard", "Mouse" });
}
This controller exposes a GET endpoint at /api/products.
Why do controllers exist?
Without a structured request-handling layer, developers might place URL parsing, input validation, business rules, database queries, and response formatting into one large method or directly into middleware. That makes the application difficult to test and change.
Controllers provide a recognizable place to:
- Receive and organize HTTP requests.
- Bind route, query, header, and body values to action parameters.
- Validate incoming data.
- Call application services.
- Translate outcomes into HTTP responses.
- Apply endpoint-level conventions, attributes, and filters.
Why should developers learn controllers?
Controllers remain common in enterprise ASP.NET Core applications, especially APIs with many endpoints, shared conventions, complex request models, or established MVC architecture. Interviewers often ask about ControllerBase, IActionResult, ActionResult<T>, [ApiController], model binding, validation, filters, and thin-controller design.
Core principle: A controller should coordinate an HTTP request, not become the place where every business rule and database operation lives.
3. Real-life analogy: a restaurant manager
Think of a restaurant manager who receives a customer's request.
- The customer request is the incoming HTTP request.
- The manager is the controller.
- The menu and order details are the request model or DTO.
- The kitchen team is the application service and domain logic.
- The inventory system is the data-access layer.
- The response to the customer is the HTTP response.
The manager takes the order, checks that the request is understandable, coordinates with the kitchen, and tells the customer what happened. The manager does not personally grow the ingredients, manage every inventory record, or define every recipe.
Similarly, a controller should validate the shape of a request, call the right service, and translate the outcome into a suitable response. Business rules belong in the appropriate application or domain layer.
4. Architecture diagram
This is a conceptual flow. The actual framework pipeline includes endpoint execution, filters, formatters, and other infrastructure. With [ApiController], invalid model state can automatically produce a 400 response before the action executes.
5. Concept explanation
5.1 What is ASP.NET Core MVC?
MVC stands for Model–View–Controller:
- Model: Data and domain concepts used by the application.
- View: The UI rendered for the user in a traditional server-rendered MVC application.
- Controller: Receives a request, coordinates work, and selects a result.
ASP.NET Core MVC supports both view-based web applications and API controllers. A Web API typically returns data such as JSON rather than rendering an HTML view.
5.2 What is a controller class?
A controller is usually a public, non-abstract class whose name ends in Controller, such as ProductsController. It commonly inherits from ControllerBase for APIs or Controller when view-related functionality is needed.
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/products")]
public sealed class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetAll()
{
return Ok(new[] { "Keyboard", "Mouse" });
}
}
Important elements:
[ApiController]enables API-specific behavior.[Route("api/products")]defines the controller's route prefix.[HttpGet]identifies the action's HTTP method.ControllerBaseprovides API-oriented helpers such asOk,NotFound, andBadRequest.GetAllis an action method selected for a matching request.
5.3 Controller vs. ControllerBase
| Feature | ControllerBase | Controller |
|---|---|---|
| Main use | Web APIs | MVC apps that may render views |
| API response helpers | Yes | Yes, through inheritance |
| View-related helpers | No full view support | Includes view-related functionality |
| Typical return | JSON, status codes, files | Views or other action results |
| Common use | REST APIs | Server-rendered MVC websites |
Controller inherits from ControllerBase. For an API-only controller, prefer ControllerBase because it communicates the intended responsibility.
5.4 What is an action method?
An action method is a public method on a controller that can be selected by routing to handle a request. It usually receives bound parameters and returns an action result.
[HttpGet("{id:int}")]
public IActionResult GetById(int id)
{
return Ok(new { ProductId = id });
}
The action receives the id route value and returns a successful response.
Not every public method on a controller should be an action. Helper methods should be private or otherwise excluded from action discovery when appropriate. Avoid exposing utility methods unintentionally.
5.5 Attribute routing
Attribute routing defines endpoint URLs close to controller actions.
[ApiController]
[Route("api/orders")]
public sealed class OrdersController : ControllerBase
{
[HttpGet]
public IActionResult GetAll() => Ok();
[HttpGet("{id:int}")]
public IActionResult GetById(int id) => Ok(new { id });
[HttpPost]
public IActionResult Create() => StatusCode(StatusCodes.Status201Created);
}
The controller prefix is combined with the action template:
GET /api/ordersGET /api/orders/42POST /api/orders
Explicit routes are particularly useful for public APIs because the URL contract is easy to see and document.
5.6 Model binding
Model binding maps values from an HTTP request to action parameters or request objects.
ASP.NET Core can bind values from several sources:
| Source | Example | Typical binding attribute |
|---|---|---|
| Route | /products/42 | [FromRoute] |
| Query string | ?page=2 | [FromQuery] |
| Request body | JSON object | [FromBody] |
| HTTP header | X-Correlation-Id | [FromHeader] |
| Form fields | HTML form data | [FromForm] |
| Dependency injection | Registered service | Usually inferred for services in API controllers |
Example:
[HttpGet("{id:int}")]
public IActionResult Get(
[FromRoute] int id,
[FromQuery] int pageSize = 20)
{
return Ok(new { id, pageSize });
}
Request: GET /api/products/42?pageSize=10
The action receives id = 42 and pageSize = 10.
Tip: Use explicit binding attributes when they make the API easier to read, especially in complex actions.
[ApiController]also infers common binding sources according to framework conventions.
5.7 Binding a request body
For JSON APIs, the request body is commonly bound to a DTO.
public sealed record CreateProductRequest(
string Name,
decimal Price);
[HttpPost]
public IActionResult Create([FromBody] CreateProductRequest request)
{
return Ok(new { request.Name, request.Price });
}
A client can send:
{
"name": "Keyboard",
"price": 49.99
}
The configured input formatter deserializes the JSON into the request object. Malformed JSON or incompatible values can produce a model-state error.
A request body is generally read by one input formatter for an action parameter. Avoid designing actions that expect multiple independent [FromBody] parameters; combine the required data into one request DTO instead.
5.8 DTOs: why not expose database entities?
A Data Transfer Object (DTO) is a type designed to carry data across a boundary, such as an HTTP API.
Avoid binding a database entity directly from a public request when it exposes fields the caller should not control. This can create over-posting or mass-assignment vulnerabilities.
For example, a database entity might contain Id, Name, Price, IsApproved, and OwnerId. A create request should generally expose only fields the client is allowed to supply, such as Name and Price.
public sealed record CreateProductRequest(
string Name,
decimal Price);
The server should set trusted values such as IDs, ownership, and approval status.
5.9 Model validation
Model validation checks whether bound data satisfies declared validation rules.
using System.ComponentModel.DataAnnotations;
public sealed class CreateProductRequest
{
[Required]
[StringLength(100, MinimumLength = 2)]
public string Name { get; init; } = string.Empty;
[Range(0.01, 100000)]
public decimal Price { get; init; }
}
Validation attributes express common input rules. More complex business rules, such as whether a discount is allowed for a specific customer, generally belong in application or domain logic.
With [ApiController], invalid model state automatically triggers a 400 response in typical API-controller scenarios. Without it, the action may need to check ModelState.IsValid manually.
Validation layers are different:
- Binding: Can the request value be converted to the target type?
- Model validation: Does the bound data satisfy declared input rules?
- Business validation: Is the operation allowed under the application's rules?
- Authorization: Is this caller permitted to perform the operation?
5.10 The [ApiController] attribute
[ApiController] enables API-specific conventions, including:
- Automatic HTTP 400 responses when model validation fails.
- Binding-source inference for many action parameters.
- API-specific error response behavior.
- Requirement for attribute routing on API controllers.
It reduces repetitive code, but it does not eliminate the need for business validation, authorization, or clear error contracts.
5.11 Action result types
Controller actions can return several result shapes. Choose a return type that communicates what the action may produce.
| Return type | Use | Example |
|---|---|---|
IActionResult | Different response types without a single declared body type | Ok, NotFound, BadRequest |
ActionResult<T> | A typed success body plus HTTP error results | ActionResult<ProductDto> |
T or Task<T> | A specific value, often serialized as the response body | ProductDto |
Task<IActionResult> | Asynchronous action with different response types | Service call then NotFound or Ok |
Task<ActionResult<T>> | Asynchronous typed API action | Typed result plus status alternatives |
Example using ActionResult<T>:
[HttpGet("{id:int}")]
public ActionResult<ProductDto> GetById(int id)
{
var product = FindProduct(id);
if (product is null)
return NotFound();
return product;
}
private static ProductDto? FindProduct(int id) =>
id == 1 ? new ProductDto(1, "Keyboard") : null;
public sealed record ProductDto(int Id, string Name);
ActionResult<ProductDto> documents the expected successful body while still allowing an HTTP error result.
5.12 Common response helpers
ControllerBase provides helpers that make response intent clear.
| Helper | Typical status | Meaning |
|---|---|---|
Ok(value) | 200 | Request succeeded |
CreatedAtAction(...) | 201 | Resource created; can include a location |
CreatedAtRoute(...) | 201 | Resource created using a named route |
NoContent() | 204 | Success with no response body |
BadRequest(...) | 400 | Invalid request |
Unauthorized() | 401 | Authentication is required or failed |
Forbid() | 403 | Caller is authenticated but not allowed |
NotFound() | 404 | Resource not found |
Conflict(...) | 409 | Request conflicts with current state |
StatusCode(...) | Specified code | Use when a dedicated helper isn't suitable |
A status code should reflect the actual result. For example, a successful create operation commonly returns 201; a successful delete with no body may return 204.
5.13 Dependency injection in controllers
Controllers should depend on interfaces or application services rather than creating dependencies manually.
public interface IProductService
{
Task<ProductDto?> GetByIdAsync(
int id,
CancellationToken cancellationToken);
}
[ApiController]
[Route("api/products")]
public sealed class ProductsController(IProductService productService)
: ControllerBase
{
[HttpGet("{id:int}")]
public async Task<ActionResult<ProductDto>> GetById(
int id,
CancellationToken cancellationToken)
{
var product = await productService.GetByIdAsync(
id, cancellationToken);
return product is null ? NotFound() : Ok(product);
}
}
This example uses primary-constructor syntax supported by modern C#. Constructor injection makes dependencies explicit and supports unit testing. Register the service in Program.cs:
builder.Services.AddScoped<IProductService, ProductService>();
ProductService is an application-defined implementation. The example assumes it exists in the project.
5.14 Asynchronous controller actions
Database and network calls are commonly I/O-bound. Use asynchronous APIs so request threads aren't unnecessarily blocked while waiting for I/O.
[HttpGet("{id:int}")]
public async Task<ActionResult<ProductDto>> GetById(
int id,
CancellationToken cancellationToken)
{
var product = await _productService.GetByIdAsync(
id, cancellationToken);
if (product is null)
return NotFound();
return Ok(product);
}
Pass the cancellation token to downstream operations when supported. Avoid .Result and .Wait() in request handling because they block threads and can reduce throughput.
5.15 Filters and controllers
MVC filters run at specific stages around action execution. They are different from middleware.
| Filter type | Purpose |
|---|---|
| Authorization filter | Authorization-related MVC stage; modern authorization is commonly configured through endpoint metadata and authorization middleware |
| Resource filter | Runs around much of MVC processing, before model binding and after result processing |
| Action filter | Runs before and after an action method |
| Exception filter | Handles certain exceptions from MVC action execution; not a universal replacement for exception-handling middleware |
| Result filter | Runs before and after action-result execution |
Filters are useful for MVC-specific concerns. Middleware is usually the better place for broad cross-cutting behavior such as global exception handling, request logging, and correlation IDs.
5.16 Controller vs. Minimal API
Controllers and Minimal APIs are both supported ways to define HTTP endpoints in ASP.NET Core.
| Aspect | Controllers | Minimal APIs |
|---|---|---|
| Organization | Classes and action methods | Endpoint registration and handler delegates |
| Common strengths | Larger APIs, MVC conventions, filters, structured actions | Small APIs, concise endpoints, route groups |
| Validation | [ApiController], model state, validation attributes | Binding/validation features depend on parameter types and configured framework support |
| Filters | MVC filter pipeline | Endpoint filters |
| Best choice | Depends on team standards and application complexity | Depends on team standards and application complexity |
Neither is universally superior. Choose the style that makes the application clearer and easier to maintain.
6. Important terminology
| Term | Meaning | Example |
|---|---|---|
| Controller | Class that groups related request actions | ProductsController |
| Action method | Controller method selected to handle a request | GetById(int id) |
ControllerBase | Base class with API-focused helpers | Ok, NotFound |
Controller | MVC base class that also supports views | return View(model) |
| Routing | Selects the endpoint for a request | [HttpGet("{id:int}")] |
| Model binding | Maps request values to action parameters | [FromQuery] int page |
| Model validation | Checks bound data against validation rules | [Required] |
| DTO | Type designed for data transfer | CreateProductRequest |
[ApiController] | Enables API-specific conventions | Automatic 400 for invalid model state |
IActionResult | Flexible action-result return type | Ok or NotFound |
ActionResult<T> | Typed response with alternative HTTP results | ActionResult<ProductDto> |
| Filter | MVC hook around a specific execution stage | Action filter |
| Dependency injection | Supplies dependencies to a controller | IProductService |
| Over-posting | Client sets fields it should not control | Sending IsApproved = true |
| Cancellation token | Signals cancellation to supported operations | CancellationToken |
| Content negotiation | Selects a response representation based on request headers and configuration | JSON response |
| Problem Details | Standardized error-response format | ProblemDetails |
7. How it works internally
Request lifecycle
- The server receives the request and creates an
HttpContext. - Middleware processes the request.
- Endpoint routing selects a controller endpoint using its route template and HTTP method metadata.
- Authentication and authorization run according to the configured pipeline.
- MVC creates the controller instance using dependency injection.
- Model binding obtains values from the route, query string, headers, form, or body.
- Model validation runs.
- If
[ApiController]detects invalid model state, the framework normally returns a 400 response without running the action. - MVC filters run at their relevant stages.
- The action method executes and calls application services.
- The action returns a result such as
Ok,NotFound, orCreatedAtAction. - Result execution and output formatting produce the HTTP response.
- The response returns through the remaining middleware.
This sequence is simplified. For invalid API model state, MVC can return a 400 response before invoking the controller action. Middleware and filters may also short-circuit execution.
What happens when the action returns NotFound()?
The controller returns an action result describing a 404 response. MVC executes the result and writes the appropriate status code and any configured body. Returning NotFound() does not mean an exception occurred; it is a normal HTTP outcome.
What happens when an exception is thrown?
An exception can propagate through MVC and the middleware pipeline. Global exception-handling middleware is typically the main mechanism for consistent error handling across endpoints. Exception filters can handle some MVC-specific exceptions but should not be treated as a universal application-wide exception strategy.
8. Syntax explained
Controller declaration
[ApiController]
[Route("api/products")]
public sealed class ProductsController : ControllerBase
{
[HttpGet("{id:int}")]
public ActionResult<ProductDto> GetById(int id)
{
return Ok(new ProductDto(id, "Keyboard"));
}
}
public sealed record ProductDto(int Id, string Name);
| Syntax | Meaning |
|---|---|
[ApiController] | Enables API-controller conventions |
[Route("api/products")] | Sets the route prefix |
ProductsController | Controller class discovered by MVC |
ControllerBase | Provides API response helpers |
[HttpGet("{id:int}")] | Maps GET requests with an integer ID |
ActionResult<ProductDto> | Typed success result plus alternative HTTP results |
Ok(...) | Returns HTTP 200 with a response body |
Binding attributes
public IActionResult Search(
[FromRoute] int categoryId,
[FromQuery] string? term,
[FromHeader(Name = "X-Client-Version")] string? clientVersion)
{
return Ok(new { categoryId, term, clientVersion });
}
[FromRoute]: bind from route values.[FromQuery]: bind from query-string values.[FromHeader]: bind from a request header.[FromBody]: bind from the request body.[FromForm]: bind form fields or uploaded form data.
Response helpers
return Ok(dto); // 200
return CreatedAtAction(nameof(GetById), new { id = dto.Id }, dto); // 201
return NoContent(); // 204
return BadRequest(); // 400
return Unauthorized(); // 401
return Forbid(); // 403
return NotFound(); // 404
return Conflict(); // 409
Use each response based on the actual operation outcome. For CreatedAtAction, ensure the referenced action and route values can generate a valid URL.
9. Code examples
9.1 Simple example: a read-only controller
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
[ApiController]
[Route("api/greetings")]
public sealed class GreetingsController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok(new
{
Message = "Hello from an ASP.NET Core controller!",
TimestampUtc = DateTimeOffset.UtcNow
});
}
}
A GET request to /api/greetings returns a JSON object with a message and timestamp. In a real project, put the controller in its own file instead of keeping it next to Program.cs.
9.2 Intermediate example: DTOs, validation, and typed results
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
[ApiController]
[Route("api/products")]
public sealed class ProductsController : ControllerBase
{
// Demo data only; replace with an application service and database.
private static readonly Dictionary<int, ProductResponse> Products = new()
{
[1] = new(1, "Keyboard", 49.99m),
[2] = new(2, "Mouse", 19.99m)
};
[HttpGet]
public ActionResult<IReadOnlyCollection<ProductResponse>> GetAll() =>
Ok(Products.Values.ToArray());
[HttpGet("{id:int:min(1)}", Name = "GetProductById")]
public ActionResult<ProductResponse> GetById(int id)
{
if (!Products.TryGetValue(id, out var product))
return NotFound();
return Ok(product);
}
[HttpPost]
public ActionResult<ProductResponse> Create(CreateProductRequest request)
{
// Demo only: not persistent and not suitable for concurrent writes.
var id = Products.Keys.DefaultIfEmpty(0).Max() + 1;
var product = new ProductResponse(id, request.Name, request.Price);
Products[id] = product;
return CreatedAtRoute("GetProductById", new { id }, product);
}
}
public sealed record ProductResponse(int Id, string Name, decimal Price);
public sealed class CreateProductRequest
{
[Required]
[StringLength(100, MinimumLength = 2)]
public string Name { get; init; } = string.Empty;
[Range(0.01, 100000)]
public decimal Price { get; init; }
}
This example demonstrates a typed response, a validated request DTO, a route constraint, and URL generation after creation. The in-memory dictionary is deliberately a teaching shortcut. In production, use a service and persistent data store, handle concurrency, and apply business validation.
9.3 Production-oriented example: thin controller with service injection
The following illustrates a controller that delegates work to an application service. The interface and DTOs are shown; the implementation is application-specific.
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
public sealed record ProductResponse(int Id, string Name, decimal Price);
public sealed class CreateProductRequest
{
[Required]
[StringLength(100, MinimumLength = 2)]
public string Name { get; init; } = string.Empty;
[Range(0.01, 100000)]
public decimal Price { get; init; }
}
public interface IProductService
{
Task<IReadOnlyCollection<ProductResponse>> GetAllAsync(
CancellationToken cancellationToken);
Task<ProductResponse?> GetByIdAsync(
int id, CancellationToken cancellationToken);
Task<ProductResponse> CreateAsync(
CreateProductRequest request, CancellationToken cancellationToken);
}
[ApiController]
[Route("api/products")]
public sealed class ProductsController(IProductService productService)
: ControllerBase
{
[HttpGet]
[ProducesResponseType(typeof(IReadOnlyCollection<ProductResponse>), StatusCodes.Status200OK)]
public async Task<ActionResult<IReadOnlyCollection<ProductResponse>>> GetAll(
CancellationToken cancellationToken)
{
var products = await productService.GetAllAsync(cancellationToken);
return Ok(products);
}
[HttpGet("{id:int:min(1)}", Name = "GetProductById")]
[ProducesResponseType(typeof(ProductResponse), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<ProductResponse>> GetById(
int id,
CancellationToken cancellationToken)
{
var product = await productService.GetByIdAsync(id, cancellationToken);
return product is null ? NotFound() : Ok(product);
}
[HttpPost]
[ProducesResponseType(typeof(ProductResponse), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<ProductResponse>> Create(
CreateProductRequest request,
CancellationToken cancellationToken)
{
var created = await productService.CreateAsync(request, cancellationToken);
return CreatedAtRoute("GetProductById", new { id = created.Id }, created);
}
}
Register the service in Program.cs:
builder.Services.AddScoped<IProductService, ProductService>();
ProductService must be implemented by the application. In a typical service implementation, the service validates domain rules, uses a repository or EF Core DbContext, and returns DTOs. The controller remains focused on HTTP concerns.
Why this is production-oriented
- Dependencies are explicit through constructor injection.
- I/O is asynchronous.
CancellationTokencan flow to supported downstream operations.- Request and response contracts are separate.
- Status codes are clear.
- The controller delegates business logic.
- Response metadata helps API documentation.
The code is a pattern, not a complete runnable application until the service implementation and registrations are supplied.
10. Recommended folder structure
ProductApi/
├── Controllers/
│ └── ProductsController.cs
├── Contracts/
│ ├── CreateProductRequest.cs
│ └── ProductResponse.cs
├── Services/
│ ├── IProductService.cs
│ └── ProductService.cs
├── Data/
│ └── AppDbContext.cs
├── Middleware/
│ └── CorrelationIdMiddleware.cs
├── Program.cs
└── ProductApi.csproj
Responsibilities
Controllers/: HTTP routing, binding, status codes, and response contracts.Contracts/: request and response DTOs.Services/: application use cases and business coordination.Data/: persistence and database configuration.Middleware/: broad cross-cutting request/response behavior.Program.cs: service registration and middleware/endpoint configuration.
This is a starting structure, not a mandatory architecture. Organize by feature or layer according to application size and team conventions.
11. Execution flow: line by line
Consider this action:
[HttpGet("{id:int:min(1)}")]
public async Task<ActionResult<ProductResponse>> GetById(
int id,
CancellationToken cancellationToken)
{
var product = await productService.GetByIdAsync(id, cancellationToken);
if (product is null)
return NotFound();
return Ok(product);
}
[HttpGet]maps the action to GET requests.{id:int:min(1)}requires an integer-shaped route value of at least 1 for the route to match.- ASP.NET Core binds the path segment to
id. - The framework supplies a cancellation token representing request cancellation where supported.
- The controller calls
IProductService.GetByIdAsync. awaityields while asynchronous I/O is pending instead of blocking the thread.- If the service returns
null, the action returns a 404 result. - Otherwise, the action returns a 200 result containing the DTO.
- MVC executes the result and serializes the response according to configured formatters.
- The response travels back through the remaining middleware to the client.
If the route value doesn't satisfy the constraint, this endpoint may not be selected at all. If the route matches but the product doesn't exist, the action explicitly returns 404.
12. Real project usage
| Industry | Controller examples | Typical responsibilities |
|---|---|---|
| E-commerce | ProductsController, OrdersController, CheckoutController | Catalog queries, order creation, checkout orchestration |
| Banking | AccountsController, TransactionsController | Account summaries, transaction history, transfer requests with strict authorization |
| Healthcare | PatientsController, AppointmentsController | Patient records, appointment scheduling, access-controlled data |
| Logistics | ShipmentsController, TrackingController | Shipment creation, tracking status, delivery updates |
| Social media | PostsController, CommentsController, ProfilesController | Publishing, comments, profile operations |
| Enterprise software | ReportsController, UsersController, TenantsController | Report requests, administration, tenant-scoped workflows |
These examples describe endpoint organization, not complete domain designs. Controllers should delegate to services, and sensitive operations require resource-level authorization and auditability.
13. Performance considerations
Memory
- Keep controllers stateless between requests.
- Avoid storing request-specific data in static fields.
- Avoid loading entire database tables when pagination is needed.
- Return DTOs containing only the fields required by the client.
CPU
- Keep action methods small and avoid unnecessary mapping or repeated calculations.
- Do not perform expensive synchronous work on request threads.
- Use validation that is appropriate to the request rather than duplicating checks across layers.
- Profile serialization and mapping when response payloads are large.
Scalability
- Use asynchronous I/O for database and network calls.
- Pass cancellation tokens to downstream APIs when supported.
- Keep controller instances request-scoped by framework behavior; don't make controller state global.
- Avoid
.Resultand.Wait()on tasks. - Use pagination, filtering, and appropriate database indexes for list endpoints.
Optimization checklist
- Use async data-access APIs.
- Project database results into DTOs rather than materializing unnecessary columns.
- Apply pagination to large collections.
- Avoid N+1 database queries in service/repository code.
- Keep response payloads appropriately sized.
- Measure endpoint latency before optimizing.
- Add logs and metrics that identify slow endpoints without logging sensitive payloads.
14. Security considerations
Common risks
Over-posting / mass assignment: A client sends fields such as IsAdmin, OwnerId, or IsApproved that it should not control.
Broken object-level authorization: A user changes a resource ID and accesses another user's data.
Excessive data exposure: The API returns internal fields or sensitive information in a DTO.
Injection and unsafe input handling: Untrusted input reaches SQL, file paths, shell commands, or other sensitive operations without safe handling.
Sensitive information in logs: Request bodies or exception details are logged without appropriate redaction.
Missing request limits: Large payloads or expensive requests consume excessive resources.
Best practices
- Use dedicated request DTOs instead of binding database entities directly.
- Authenticate and authorize sensitive endpoints.
- Enforce resource ownership and tenant access in application logic.
- Validate input, but don't mistake validation for authorization.
- Use parameterized database access or safe ORM APIs.
- Return only necessary fields.
- Use HTTPS and secure secret management.
- Apply rate limits and request-size limits where appropriate.
- Use global exception handling and safe error responses.
- Avoid logging credentials, tokens, payment data, or sensitive health information.
- Protect state-changing operations against relevant CSRF risks when using cookie authentication and browser-based flows.
- Add audit logging for sensitive operations where required.
- Test unauthorized, cross-tenant, malformed, and over-posted requests.
Security warning: A controller action that accepts an
idand retrieves a record must still verify that the current caller may access that record. Knowing or guessing an ID is not authorization.
15. Ten common beginner mistakes
1. Putting business logic in the controller
Why it happens: The action is the first place where the request is handled.
Fix: Delegate business use cases to application services. Keep the controller responsible for HTTP concerns.
2. Returning 200 OK for every outcome
Why it happens: A single response helper feels simpler.
Fix: Use meaningful status codes: 201 for creation, 204 for success without a body, 400 for invalid input, 404 for missing resources, and 409 for state conflicts when appropriate.
3. Binding database entities directly from requests
Why it happens: It avoids creating DTOs.
Fix: Use request DTOs that expose only fields the client is allowed to provide.
4. Forgetting model validation
Why it happens: Developers assume type conversion is enough.
Fix: Add validation attributes or explicit validators. Understand automatic validation behavior when [ApiController] is applied.
5. Confusing IActionResult and ActionResult<T>
Why it happens: Both can return HTTP results.
Fix: Use IActionResult when many result shapes are possible without a single typed body. Use ActionResult<T> when there is a clear success DTO plus error responses.
6. Using .Result or .Wait() in actions
Why it happens: Synchronous-looking code may seem easier.
Fix: Use async/await and asynchronous downstream APIs to avoid blocking request threads.
7. Forgetting cancellation
Why it happens: The action works without a token.
Fix: Accept CancellationToken and pass it to database and network APIs that support cancellation.
8. Returning too much data
Why it happens: Returning the entire entity is convenient.
Fix: Use response DTOs, pagination, and field selection where needed.
9. Treating a filter as a replacement for middleware
Why it happens: Both can run code around requests.
Fix: Use middleware for broad HTTP-pipeline concerns and filters for MVC-specific execution stages.
10. Assuming authentication alone protects a resource
Why it happens: The user is signed in, so the endpoint appears safe.
Fix: Apply authorization policies and resource-level checks, including ownership and tenant membership.
16. Production best practices
- Keep controllers thin and focused on HTTP concerns.
- Use constructor injection for application services.
- Use request and response DTOs to define stable API contracts.
- Apply
[ApiController]for API controllers where its conventions fit. - Use attribute routing for explicit public API routes.
- Return status codes that reflect the actual outcome.
- Prefer
ActionResult<T>when a typed success response is appropriate. - Use asynchronous I/O for database and network work.
- Pass cancellation tokens downstream.
- Validate request input and enforce domain rules in the correct layer.
- Keep authorization separate from model validation.
- Enforce resource-level and tenant-level access checks.
- Avoid exposing persistence entities directly.
- Keep secrets and sensitive fields out of response DTOs.
- Centralize exception handling with appropriate middleware.
- Use filters only when their MVC-specific lifecycle is useful.
- Document response types with OpenAPI metadata where appropriate.
- Use pagination for large collections.
- Avoid blocking calls such as
.Resultand.Wait(). - Keep controller methods small enough to test and review.
- Add integration tests for routing, model binding, validation, and status codes.
- Add unit tests for application services and business rules.
- Avoid storing mutable request state in static fields.
- Use consistent error responses, such as Problem Details, across the API.
- Log useful diagnostics while redacting sensitive data.
- Review over-posting risks in every state-changing action.
- Use rate limiting and request limits where the threat model requires them.
- Keep API route changes compatible or version them deliberately.
- Don't catch exceptions merely to return 500 from every action; use centralized handling unless local recovery is meaningful.
- Keep controller tests focused on HTTP behavior and service interaction, not duplicated domain rules.
17. Interview questions and answers
Beginner questions
1. What is a controller in ASP.NET Core?
A controller is a class that groups related action methods. Routing selects an action for a request; the action coordinates work and returns an HTTP result.
2. What is an action method?
A controller method that routing can select to handle a request. It receives bound parameters and returns a result.
3. What is the difference between Controller and ControllerBase?
ControllerBase provides API-focused helpers. Controller inherits from it and adds view-related functionality for MVC applications.
4. What does [ApiController] do?
It enables API-specific conventions such as automatic 400 responses for invalid model state, binding-source inference, and API-oriented behavior. It doesn't replace business validation or authorization.
5. What is model binding?
It maps request data—such as route values, query strings, headers, forms, and JSON bodies—to action parameters or request models.
6. What is model validation?
It checks bound input against declared validation rules, such as [Required], [StringLength], and [Range].
7. What is a DTO?
A Data Transfer Object is a type designed to carry data across a boundary. Request DTOs control which fields clients can submit; response DTOs control which fields the API exposes.
8. What is IActionResult?
An action-result abstraction that lets an action return different HTTP result types, such as 200, 400, or 404.
9. What is ActionResult<T>?
A typed action result that communicates the expected success body type while allowing alternative HTTP results such as NotFound().
10. Why should controllers use dependency injection?
It makes dependencies explicit, improves testability, and avoids manually constructing services inside actions.
Intermediate questions
11. What is the difference between [FromRoute] and [FromQuery]?
[FromRoute] binds from URL path parameters; [FromQuery] binds from the query string. For example, /products/42?page=2 can bind id from the route and page from the query.
12. Why use request DTOs instead of entity classes?
DTOs define a controlled API contract, avoid exposing persistence details, and reduce over-posting risks by limiting which fields the client can set.
13. What happens when model validation fails with [ApiController]?
In common API-controller scenarios, ASP.NET Core automatically returns a 400 response and doesn't invoke the action. Applications can customize the invalid-model-state response behavior.
14. When should an action return NotFound()?
When the requested resource doesn't exist or the application intentionally presents it as unavailable. Don't return 200 with a misleading empty object when the contract means the resource is absent.
15. When should you return 201 Created?
When the request successfully creates a resource. A response can include a Location header generated through CreatedAtAction or CreatedAtRoute.
16. What is the difference between middleware and MVC filters?
Middleware runs in the HTTP pipeline and can apply broadly across endpoints. Filters run at MVC-specific stages around resource, action, exception, or result processing.
17. Why make controller actions asynchronous?
Asynchronous I/O avoids blocking a request thread while waiting for a database or network operation, improving server throughput under concurrent load.
18. What is over-posting?
Over-posting occurs when a client submits fields that should not be controlled by the client, such as an approval flag or owner ID. Use request DTOs and assign trusted fields on the server.
19. How do you pass a cancellation token to a controller action?
Accept a CancellationToken parameter and pass it to supported service, database, or HTTP operations so work can stop when cancellation is requested.
20. How do you keep controllers maintainable?
Keep actions thin, use services for application logic, use DTOs, centralize error handling, follow consistent status-code conventions, and test HTTP behavior.
Advanced questions
21. Explain the lifecycle of a controller request.
Middleware processes the request, routing selects the controller endpoint, MVC creates the controller, binds and validates parameters, executes filters and the action, then executes the action result and writes the response. Exact stages depend on configuration and short-circuit behavior.
22. Why is [ApiController] not a replacement for business validation?
It helps validate request shape and declared model rules. Domain decisions—such as inventory availability, account limits, or user permissions—require application logic and sometimes data-store checks.
23. How do you prevent IDOR in controller actions?
Authenticate the caller, authorize access to the specific resource, verify ownership or tenant membership, and test attempts to access another user's records. Route constraints and unguessable IDs are not sufficient controls.
24. What is the difference between Unauthorized() and Forbid()?
401 indicates that authentication is missing or invalid, or that authentication is required. 403 indicates the caller is authenticated but not permitted. Authentication schemes may influence the exact response behavior.
25. Why shouldn't every action catch every exception?
It duplicates error handling, can hide useful diagnostic context, and creates inconsistent responses. Prefer centralized exception-handling middleware; catch locally only when the action can meaningfully recover or translate a known failure.
26. What is content negotiation?
Content negotiation determines the response representation based on factors such as the request's Accept header, configured formatters, and application settings. JSON is common for Web APIs, but behavior depends on configuration.
27. How would you design consistent API errors?
Use centralized exception handling, stable error contracts such as Problem Details, appropriate status codes, validation details that are safe to expose, and structured logs that retain diagnostics without leaking sensitive data.
28. How do you test a controller?
Unit-test controller behavior and service interactions where useful, but use integration tests with the ASP.NET Core test host to verify routing, binding, validation, filters, serialization, authentication, and actual status codes.
29. How do controller lifetimes affect state?
Controllers are created by MVC for request handling and should generally be treated as request-specific objects. Do not use static mutable fields to store request data; use the correct service lifetime and concurrency-safe persistence instead.
30. When would you choose controllers over Minimal APIs?
Choose based on maintainability, team conventions, and application needs. Controllers can be a natural fit for larger APIs that benefit from class-based organization, MVC filters, and established conventions. Minimal APIs can be concise for smaller or feature-oriented endpoints. Both can be production-ready.
18. Hands-on exercise
Build a Product API using controllers.
Requirements
GET /api/productsreturns a collection of products.GET /api/products/{id:int}returns one product or 404.POST /api/productscreates a product and returns 201 with a generatedLocationURL.- Validate the product name and price.
- Use separate request and response DTOs.
- Inject an
IProductServiceinto the controller. - Use asynchronous service methods and pass a cancellation token.
- Return consistent status codes.
- Write integration tests for valid input, invalid input, missing resources, and unsupported methods.
- Confirm that the client cannot set fields such as
Id,OwnerId, orIsApprovedthrough the create request.
Acceptance criteria
| Scenario | Expected result |
|---|---|
| List products | 200 OK |
| Existing product | 200 OK with DTO |
| Missing product | 404 Not Found |
| Valid create request | 201 Created and Location |
| Invalid name or price | 400 Bad Request under normal [ApiController] validation behavior |
| Malformed JSON | Appropriate 400 response under standard API-controller behavior |
| Unsupported HTTP method | Appropriate 405 behavior when the endpoint configuration detects it |
| Unauthorized resource access | 401 or 403, according to authentication and authorization behavior |
Stretch goal: Add an update endpoint with optimistic concurrency handling and test a conflicting update response such as 409 Conflict.
19. Mini project: production-style product management API
Goal
Create a small API that demonstrates controller design, request DTOs, service injection, validation, status codes, URL generation, and integration testing.
Suggested endpoints
| Method | Route | Purpose |
|---|---|---|
| GET | /api/products | List products with pagination |
| GET | /api/products/{id:int} | Get one product |
| POST | /api/products | Create a product |
| PUT | /api/products/{id:int} | Update a product |
| DELETE | /api/products/{id:int} | Delete a product |
Suggested architecture
Implementation plan
- Create an ASP.NET Core Web API project targeting .NET 9 or later.
- Add a
ProductsController. - Create
CreateProductRequest,UpdateProductRequest, andProductResponseDTOs. - Add validation rules to request DTOs.
- Define
IProductServiceand implement it inProductService. - Register services through dependency injection.
- Use EF Core or a repository abstraction for persistence.
- Use
ActionResult<T>for typed responses. - Use
CreatedAtRouteorCreatedAtActionafter creation. - Add centralized exception handling and a consistent error response format.
- Add authentication and resource-level authorization for protected operations.
- Write integration tests using the ASP.NET Core test host.
- Add OpenAPI response metadata and verify the generated API description.
- Review the controller to ensure business logic is not duplicated inside action methods.
Example action pattern
[HttpGet("{id:int:min(1)}")]
public async Task<ActionResult<ProductResponse>> GetById(
int id,
CancellationToken cancellationToken)
{
var product = await productService.GetByIdAsync(id, cancellationToken);
if (product is null)
return NotFound();
return Ok(product);
}
The controller handles HTTP concerns; the service owns the application use case. Keep persistence and domain decisions out of the action.
20. Quiz: multiple-choice questions
Q1. What is the main responsibility of a controller?
A. Replace the database
B. Coordinate HTTP request handling and return a result
C. Compile C# source code
D. Manage operating-system processes
Correct answer: B
Explanation: Controllers receive routed requests, coordinate application services, and select HTTP responses. They should not replace persistence or domain layers.
Q2. Which base class is commonly preferred for API-only controllers?
A. ControllerBase
B. DbContext
C. HttpClient
D. BackgroundService
Correct answer: A
Explanation: ControllerBase provides API-oriented helpers without the view-related functionality of Controller.
Q3. What does [ApiController] commonly do when model validation fails?
A. Always returns 500
B. Automatically returns 400 in standard API-controller scenarios
C. Deletes the request
D. Skips routing
Correct answer: B
Explanation: Automatic invalid-model-state responses reduce repetitive validation checks in API actions. Business validation remains necessary.
Q4. Which binding attribute reads a value from the query string?
A. [FromBody]
B. [FromQuery]
C. [FromServices]
D. [FromFormFile]
Correct answer: B
Explanation: [FromQuery] binds query-string values such as ?page=2.
Q5. Why use request DTOs?
A. To avoid HTTP status codes
B. To expose every database column
C. To control the fields clients may submit
D. To replace authorization
Correct answer: C
Explanation: Request DTOs define an explicit input contract and help prevent over-posting.
Q6. Which status code is commonly appropriate after successfully creating a resource?
A. 201
B. 204 only
C. 404
D. 500
Correct answer: A
Explanation: 201 Created communicates successful resource creation and can include a Location header.
Q7. What is a major benefit of asynchronous controller actions?
A. They remove the need for validation
B. They avoid blocking a request thread during supported I/O waits
C. They guarantee every query is faster
D. They disable cancellation
Correct answer: B
Explanation: Async I/O improves scalability under concurrent workloads; it doesn't automatically make an individual operation faster.
Q8. What is over-posting?
A. Sending a request twice
B. A client setting fields it should not control
C. Returning a 204 response
D. Adding a route prefix
Correct answer: B
Explanation: Dedicated request DTOs and server-controlled field assignment help prevent over-posting.
Q9. Which is usually the best place for broad application-wide exception handling?
A. Every controller action separately
B. Global exception-handling middleware
C. A route parameter
D. A database column
Correct answer: B
Explanation: Middleware provides consistent handling across endpoints. Filters can handle some MVC-specific cases but are not a universal substitute.
Q10. Does authentication alone guarantee that a user may access a particular record?
A. Yes, always
B. Only if the ID is an integer
C. No; resource-level authorization may still be required
D. Only for GET requests
Correct answer: C
Explanation: The application must enforce ownership, tenant boundaries, and permission policies for individual resources.
21. Summary
One-minute revision
A controller groups related HTTP actions. Routing selects the action, model binding maps request values to parameters, validation checks declared input rules, and the action coordinates application services before returning a result. ControllerBase is common for APIs; Controller adds view support. [ApiController] enables conventions such as automatic 400 responses for invalid model state. Use DTOs, dependency injection, async I/O, meaningful status codes, centralized exception handling, and resource-level authorization.
Five-minute revision
- Controller: Organizes related request-handling actions.
- Action: Handles a selected request and returns a result.
ControllerBase: API-focused helpers.Controller: MVC base class with view support.- Routing: Selects the endpoint.
- Model binding: Maps request data to action parameters.
- Model validation: Checks declared input rules.
- DTO: Defines an explicit request or response contract.
[ApiController]: Enables API-specific conventions.IActionResult: Flexible action-result type.ActionResult<T>: Typed success body plus alternative results.- Dependency injection: Supplies services to the controller.
- Async I/O: Avoids blocking request threads during I/O waits.
- Filters: Run at MVC-specific lifecycle stages.
- Middleware: Handles broad request/response pipeline concerns.
- Security: Authentication is not the same as resource authorization.
Bullet-point summary
- Keep controllers focused on HTTP responsibilities.
- Delegate use cases to application services.
- Use request DTOs to limit client-controlled fields.
- Use response DTOs to avoid exposing internal data.
- Apply validation and enforce business rules at the appropriate layer.
- Choose status codes that reflect the operation outcome.
- Prefer async I/O and propagate cancellation.
- Centralize exception handling.
- Test routing, binding, validation, serialization, and authorization.
- Avoid over-posting and insecure direct object references.
Memory tricks
- Controller = Coordinator. It connects the request to application behavior.
- Binding = Bring values in. Route, query, header, form, or body.
- Validation = Is the input acceptable? Check shape and declared rules.
- Service = Solve the use case. Keep business behavior outside the controller.
- Result = Report the outcome. Return a meaningful status and response body.
- Authentication = Who are you? Authorization = May you do this?
Flashcards
| Front | Back |
|---|---|
| What is a controller? | A class grouping related HTTP action methods. |
ControllerBase vs Controller? | API helpers vs API helpers plus view support. |
What does [ApiController] provide? | API conventions, including automatic 400 for invalid model state. |
| What is model binding? | Mapping request values to action parameters or DTOs. |
| Why use DTOs? | Control request fields and response exposure. |
IActionResult vs ActionResult<T>? | Flexible results vs typed success body plus alternatives. |
| Why use async actions? | Avoid blocking threads while supported I/O is pending. |
| What is over-posting? | Client submits fields it should not control. |
| Middleware vs filters? | Broad HTTP pipeline vs MVC-specific execution stages. |
| Does authentication prove record ownership? | No; resource-level authorization is separate. |
22. Cheat sheet
| Need | Use |
|---|---|
| API controller base | ControllerBase |
| View-capable MVC controller | Controller |
| API conventions | [ApiController] |
| Controller route prefix | [Route("api/products")] |
| GET action | [HttpGet] |
| Route parameter | [HttpGet("{id:int}")] |
| Query binding | [FromQuery] |
| Route binding | [FromRoute] |
| JSON body binding | [FromBody] |
| Header binding | [FromHeader] |
| Form binding | [FromForm] |
| Typed success/error result | ActionResult<ProductResponse> |
| Success | Ok(value) |
| Created resource | CreatedAtAction(...) or CreatedAtRoute(...) |
| No response body | NoContent() |
| Invalid request | BadRequest(...) |
| Unauthenticated | Unauthorized() |
| Authenticated but forbidden | Forbid() |
| Missing resource | NotFound() |
| State conflict | Conflict(...) |
| Dependency injection | Constructor injection |
| Async request handling | async Task<ActionResult<T>> |
| Request cancellation | CancellationToken |
| Broad exception handling | Exception-handling middleware |
| MVC-specific lifecycle hook | MVC filter |
| API contract | Request and response DTOs |
23. Comparison table
Controller vs ControllerBase
| Aspect | Controller | ControllerBase |
|---|---|---|
| API response helpers | Yes | Yes |
| View support | Yes | No full view support |
| Typical use | MVC website | Web API |
| Inheritance | Inherits from ControllerBase | Base API-oriented controller class |
IActionResult vs ActionResult<T>
| Aspect | IActionResult | ActionResult<T> |
|---|---|---|
| Typed success body | Not expressed by the return type | Expressed as T |
| Multiple HTTP results | Yes | Yes |
| Best fit | Varied result shapes without a single declared body | Typed API response plus error results |
| Example | IActionResult Get() | ActionResult<ProductResponse> GetById() |
Controllers vs Minimal APIs
| Aspect | Controllers | Minimal APIs |
|---|---|---|
| Endpoint organization | Controller classes and actions | Route registrations and handlers |
| Common use | Larger APIs, MVC conventions, filters | Concise endpoint definitions, route groups |
| Request handling | Model binding and MVC conventions | Minimal API binding conventions |
| Extensibility | MVC filters and conventions | Endpoint filters and endpoint conventions |
| Choice | Based on team and application needs | Based on team and application needs |
Middleware vs MVC filters
| Aspect | Middleware | MVC filters |
|---|---|---|
| Scope | HTTP pipeline, often app-wide | MVC action/result lifecycle |
| Examples | Exception handling, request logging | Action-specific validation or result behavior |
| Runs for non-MVC endpoints? | Usually, if registered in the pipeline | No, filters are part of MVC execution |
| Best use | Broad cross-cutting behavior | MVC-specific behavior |
Model validation vs business validation
| Aspect | Model validation | Business validation |
|---|---|---|
| Purpose | Check request data rules | Check domain/use-case rules |
| Example | Name required, price range | Product can be sold in this region |
| Typical location | DTO validation attributes or validators | Application/domain service |
Automatically handled by [ApiController]? | Many model-state errors produce automatic 400 | No |
24. Key takeaways
- Controllers organize HTTP request handling into action methods.
ControllerBaseis usually appropriate for API-only controllers.- Routing, binding, validation, business logic, and authorization have distinct responsibilities.
- DTOs help define safe, stable API contracts.
[ApiController]reduces repetitive model-state handling.ActionResult<T>makes typed success responses clear.- Use dependency injection and keep actions thin.
- Use async I/O and cancellation where supported.
- Centralize exception handling and use consistent error responses.
- Authentication doesn't replace resource-level authorization.
- Integration tests are essential for verifying real HTTP behavior.
25. Revision checklist
- I can explain the role of a controller.
- I understand
ControllerversusControllerBase. - I can define controller routes and action methods.
- I understand model binding sources.
- I can create request and response DTOs.
- I understand
[ApiController]and automatic validation responses. - I can choose between
IActionResultandActionResult<T>. - I can return appropriate HTTP status codes.
- I can inject an application service into a controller.
- I can write asynchronous actions and pass cancellation tokens.
- I understand middleware versus MVC filters.
- I can explain over-posting and prevent it with DTOs.
- I know how to enforce resource-level authorization.
- I can test routing, binding, validation, and responses.
- I can keep business logic out of controller actions.
26. Further reading
Continue with these related Logic Lense Roadmaps articles:
- Middleware Pipeline — Understand request processing around endpoint execution.
- Routing in ASP.NET Core — Learn route templates, constraints, route groups, and URL generation.
- Minimal APIs in ASP.NET Core — Define endpoints without controller classes.
- Razor Pages in ASP.NET Core — Learn page-focused request handling.
- Dependency Injection in ASP.NET Core — Register and inject application services.
- Model Binding and Validation — Explore request binding and input validation in more depth.
- Authentication and Authorization in ASP.NET Core — Protect endpoints and resources.
- REST API Design — Build predictable resource-oriented APIs.
- Exception Handling in ASP.NET Core — Produce consistent, safe error responses.
- Testing ASP.NET Core APIs — Verify endpoints using unit and integration tests.
Last updated 10/25/2026
Your notes
Sign in to save personal notes on this topic — they'll sync across your devices.
Was this tutorial helpful?
Help us create more free learning resources. Learn more
