Routing Process in WebAPI
Routing Process in WEB API
Web API routing is the mechanism that matches incoming HTTP requests to specific executable endpoints.
This process occurs through two primary architectural styles: Controller-based Routing and Minimal API Routing
The Routing Middleware Pipeline
The process works in two main phases within the ASP.NET Core middleware pipeline:
- UseRouting: Matches the incoming request's URL to an endpoint defined in the app.
- UseEndpoints (or app.MapControllers): Executes the delegate associated with the matched endpoint.
First style
1. Attribute Routing (for Controllers) or Controller-based Routing
Attribute routing is the standard and recommended approach for controller-based Web APIs, offering explicit control over URI structure.
Definition: Routes are defined using attributes (e.g., [Route(...)], [HttpGet], [HttpPost]) directly on the controller class and its action methods.
[ApiController]
[Route("api/[controller]")] // Base route: /api/products
public class ProductsController : ControllerBase
{
// Matches GET /api/products
[HttpGet]
public IActionResult List() { ... }
// Matches GET /api/products/{id} (where {id} is an integer)
[HttpGet("{id:int}")]
public IActionResult GetProduct(int id) { ... }
}
Key Aspects:
HTTP Verb Matching:Attributes like[HttpGet], [HttpPost], [HttpPut], [HttpDelete]ensure the action only handles requests with the specified HTTP method.Route Parameters and Constraints:Placeholders in the route template (e.g., {id}) bind automatically to method parameters. Constraints (e.g., {id:int}) enforce data types, preventing invalid requests from reaching your code.Configuration:You enable attribute routing in Program.cs by callingapp.MapControllers().
Second style
2. Minimal API Routing
Minimal APIs: A lightweight alternative to controllers where routes are defined fluently in Program.cs using methods like app.MapGet() or app.MapPost().
Definition: Routes are mapped using extension methods corresponding to HTTP verbs (e.g., app.MapGet, app.MapPost). Example:
var builder = WebApplication.CreateBuilder(args);
// ... service configurations ...
var app = builder.Build();
// Matches GET /users/{userId}/books/{bookId}
app.MapGet("/users/{userId}/books/{bookId}", (int userId, int bookId) =>
{
return $"User ID: {userId}, Book ID: {bookId}";
});
app.Run();
Key Aspects:
Simplicity: Routes and logic are often defined in one place, using lambdas or local functions.
Automatic Binding: Values from the URL path, query string, or request body are automatically bound to the method parameters.
Note:
Web API routing is very similar to MVC routing. The main difference is that Web API uses the HTTP verb, not the URI path, to select the action. We can also use MVC-style routing in Web API.
Q1: what is difference between APIcontroller and controllerbase
In ASP.NET Core, the primary difference is their specialized purpose: ControllerBase is for building APIs, while Controller is for building web pages with HTML views.
1. Key Differences
| Feature | ControllerBase | Controller |
|---|---|---|
| Purpose | RESTful APIs (returns JSON/XML data) | MVC Web Apps (returns HTML views) |
| Inheritance | Base class for all controllers | Inherits from ControllerBase |
| View Support | None (no View(), PartialView()) | Full support (View(), ViewData, TempData) |
| Weight | Lightweight; contains only API essentials | Heavier; includes view-rendering logic |
2. When to Use Which
Use ControllerBasewhen buildingWeb APIs.It provides access toHttpContext, Request, Response,andhelper methodslike Ok(), BadRequest(), and NotFound() without the overhead of the view engine.Use Controllerwhen buildingtraditional web applicationsthat serve Razor views or when you need a single controller to handle both HTML pages and data endpoints.
3. The Role of [ApiController]
While not a base class, the
[ApiController]attribute is almost always used withControllerBaseto enable specialized API behaviors:Automatic Model Validation:Automatically returns a400 Bad Requestif the model is invalid, so you don't have to manually checkModelState.IsValid.Binding Source Inference:Automatically infers if a parameter should come from the request body ([FromBody]) or query string ([FromQuery]).Mandatory Attribute Routing:Requires you to use[Route]attributes on actions rather than relying on global conventional routing.
Non-Actions
In ASP.NET Web API and MVC, a "non-action" refers to a public method within a controller that you do not want to be exposed and invoked as an HTTP endpoint via URL routing
// Not an action method.
[NonAction]
public string GetPrivateData() { ... }
Comments
Post a Comment