Volume 2 · Chapter 6 — ASP.NET Core Enterprise Development

MVC and Endpoint Routing

Goutham Mayaluri 7 min read .NETC#ASP.NET CoreRouting

6.1 Introduction

ASP.NET Core MVC structures web applications and APIs into controllers, actions, model binding, filters, and validation. Even in API-focused systems these concepts are fundamental, and Endpoint Routing is the modern system that connects incoming requests to the right handler. The recurring theme is that controllers should stay thin - handling HTTP concerns and delegating business logic to services - so the API layer remains maintainable as it grows to hundreds of endpoints across many teams.

6.2 The Request-to-Response Flow

flowchart TB
  Req["HTTP Request"] --> Route["Endpoint Routing (match URL + method)"]
  Route --> Bind["Model Binding + Validation"]
  Bind --> Action["Controller Action (thin)"]
  Action --> Svc["Application Service (business logic)"]
  Svc --> Result["IActionResult"]
  Result --> Resp["HTTP Response"]

6.3 Controllers, Model Binding, and Validation

A controller receives requests, coordinates with services, and returns results. Model binding automatically maps request data (route, query, headers, body) into method parameters and objects, and model validation (data annotations, FluentValidation, or custom rules) checks the input before business logic runs.


[ApiController, Route("api/customers")]
public sealed class CustomersController(ICustomerService service) : ControllerBase
{
    // Model binding extracts id from the route; [ApiController] auto-returns 400 on invalid model.
    [HttpGet("{id:guid}")]
    public async Task<ActionResult<CustomerDto>> Get(Guid id, CancellationToken ct)
    {
        var customer = await service.GetAsync(id, ct);
        return customer is null ? NotFound() : Ok(customer);   // thin: delegate + shape response
    }

    [HttpPost]
    public async Task<IActionResult> Create(CreateCustomerRequest request, CancellationToken ct)
    {
        var id = await service.CreateAsync(request, ct);
        return CreatedAtAction(nameof(Get), new { id }, null);  // 201 with Location
    }
}

public sealed class CreateCustomerRequest
{
    [Required, StringLength(100)] public string Name { get; set; } = "";
    [EmailAddress] public string Email { get; set; } = "";
}

6.4 Endpoint Routing

Endpoint Routing separates routematchingfrom endpointexecution: routing runs early in the pipeline to determine which endpoint will handle the request (and its metadata), so later middleware (like authorization) can make decisions based on the selected endpoint before it executes. Attribute routing defines routes directly on controllers and actions, and route constraints ({id:guid}) refine matching.

6.5 Filters

Filters run within the MVC action pipeline for concerns tied to actions - authorization filters (action- level security), action filters (before/after execution), exception filters (error handling), and result filters (response processing). Unlike middleware, filters have access to MVC context (the action, bound arguments, and result) and can be scoped to specific controllers or actions.

6.6 MVC Controllers vs Minimal APIs

MVC Controllers Minimal APIs
Rich features: filters, model binding, conventions Lightweight, low ceremony
Structured for large apps and teams Ideal for small, focused services
More overhead per request Lower per-request overhead
Senior Interview Question

How does ASP.NET Core select which endpoint handles a request?

Through endpoint routing, which happens in two phases separated in the pipeline. First,UseRoutingruns the endpoint matcher: it takes the incoming request’s path and HTTP method and evaluates them against all registered endpoints, matching route templates (including parameters and constraints like{id:guid}), the HTTP method, and any other metadata, and it selects the best-matching endpoint - resolving ambiguities by specificity (more specific routes and constraints win). Importantly, it onlyselectsthe endpoint and attaches it (and its metadata) to theHttpContextat this point; it does not execute it yet. This separation is deliberate and valuable: because the chosen endpoint and its metadata are known before execution, middleware that runs betweenUseRoutingandUseEndpoints- notably authorization - can make decisions based on the selected endpoint (for example reading its authorization policy) before the endpoint runs. Then, later in the pipeline, endpoint execution invokes the selected endpoint - model binding populates parameters, filters run, and the action executes. So the selection factors are the URL pattern, HTTP method, route constraints, and endpoint metadata, with the most specific match chosen, and the key design point is that matching is decoupled from execution so the pipeline can act on knowledge of the target endpoint in between. Understanding this explains why authorization sits betweenUseRoutingand the endpoint, and how attribute routing and constraints drive which action is chosen.

Senior Interview Question

When would you choose Minimal APIs over MVC controllers?

I choose Minimal APIs when I want low ceremony and minimal per-request overhead for small, focused services - lightweight microservices, simple CRUD or webhook endpoints, and high-throughput APIs where the reduced overhead matters. Minimal APIs let you define endpoints as concise lambdas mapped directly to routes, without the controller-class structure, and they have a lighter request pipeline than the full MVC filter model, so they’re fast to write and fast to run for straightforward cases. I choose MVC controllers for larger, structured applications and teams, where the richer feature set pays off: the full filter pipeline (authorization, action, exception, result filters), conventions, robust model binding and validation integration, and the organizational structure of controllers grouping related actions - all of which help manage complexity and consistency across many endpoints and developers. So the decision is essentially simplicity and performance for small/focused services (Minimal APIs) versus structure, rich features, and maintainability for large enterprise applications (controllers). That said, the gap has narrowed - Minimal APIs have gained filters, validation improvements, and grouping - so for new services I weigh the team’s familiarity and the app’s expected complexity; a large enterprise API with many cross-cutting concerns and teams usually benefits from controllers, while a small independent service is cleaner as a Minimal API. It’s not that one is universally better; it’s matching the ceremony and feature set to the size and needs of the service.

Principal Engineer Question

An enterprise API has hundreds of endpoints with business logic, validation, and data access inside controllers, making change risky. How do you improve it?

The root problem is that controllers have taken on responsibilities they shouldn’t have - business rules, validation, and data access - violating separation of concerns and making the API layer a fragile, untestable dumping ground where every change risks unrelated endpoints. I’d drive it back to thin controllers by moving concerns to the right layers. Controllers should handle only HTTP concerns: receiving the request, delegating to an application service, and shaping the HTTP response (status codes, DTOs). So I’d extract the business logic and workflows into an application/service layer (or, for a complex domain, an application layer with command/query handlers per Clean Architecture and DDD), and move data access behind repositories or the service layer, so controllers no longer touchDbContextdirectly. Validation moves to a consistent layer - data annotations or FluentValidation at the request- model boundary, with business-rule validation in the domain/application layer - applied uniformly rather than hand-coded per action. I’d standardize the API contracts: consistent DTOs (never exposing entities), a standard error contract via central exception handling, consistent pagination and versioning conventions, so consumers see a coherent API and internal models can evolve independently. I’d do this incrementally, not as a big-bang rewrite - refactor endpoint by endpoint, introducing the service layer and DTOs behind the existing routes while keeping the API stable, backed by tests so refactoring is safe (thin controllers plus a service layer are far more testable). I’d also add shared templates and guidelines so new endpoints follow the pattern, preventing regression. The outcome is controllers that are thin and uniform, business logic that lives in a tested, reusable service/domain layer, consistent contracts, and changes whose blast radius is contained to the relevant service rather than rippling through the API layer - which is what makes a large, multi-team API maintainable over time.

6.7 Production Scenario

An enterprise API developed by multiple teams has controllers stuffed with business logic, validation, and database calls, so any change is risky and hard to test. The team refactors incrementally toward thin controllers: business logic moves into an application service layer, data access behind repositories, validation to a consistent request-model layer, and API contracts (DTOs, error shape, versioning) are standardized - contained blast radius, testable logic, and a coherent API surface, without a big-bang rewrite.

Chapter Revision Notes

  • Keep controllers thin - HTTP concerns only; delegate business logic to services.
  • Model binding maps request data to parameters; validation checks input before logic runs.
  • Endpoint routing separates matching from execution, so authorization can act on the chosen endpoint.
  • Filters handle MVC-scoped cross-cutting concerns with access to action context.
  • Minimal APIs for small/focused services; controllers for large, structured applications.