IConfiguration vs IOptions NET
Synchronous and Asynchronous in .NET Core
Model Binding and Validation in ASP.NET Core
ControllerBase vs Controller in ASP.NET Core
ConfigureServices and Configure methods
IHostedService interface in .NET Core
ASP.NET Core request processing
| Filters in ASP.NET Core | Implementing JWT Authentication in ASP.NET Core | |
Routing in ASP.NET Core Web API |
In ASP.NET Core, routing is the process of matching incoming HTTP requests to executable endpoints in your application. It analyzes a request's URL and determines which piece of application logic, such as a controller action or a minimal API endpoint, should handle it. This system is a fundamental component of the framework and is configured in your application's middleware pipeline.
pattern: "{controller=Home}/{action=Index}/{id?}"
Routing in a Web API follows a pattern-matching system to direct requests to the correct controller and method. The modern approach in ASP.NET Core Web API is to use attribute routing, which defines routes directly on the controllers and their action methods using attributes.
https://example.com/api/products/1.UseRouting(), which adds route-matching capabilities to the pipeline.
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers(); // Enables attribute routing
});
[HttpGet("api/products/{id}")])"api/{controller}/{action}/{id?}")
[Route] attribute that matches the first part of the URL (e.g., api/[controller]). It then finds an action method with an attribute (e.g., [HttpGet("{id}")]) that matches the rest of the URL and the HTTP method.{id}, are used to extract values from the URL and passed as arguments to the selected action method.
[HttpGet("api/products/{id}")]
public IActionResult GetProduct(int id) { ... }
UseRouting() and UseEndpoints() have run (including authorization), the UseEndpoints() middleware executes the matched endpoint.| Mode | Description |
|---|---|
| Conventional | Uses a central route template. Best for MVC apps. |
| Attribute | Uses [HttpGet], [Route], etc. directly on actions. Preferred for APIs. |
| Endpoint Routing | Introduced in ASP.NET Core 3.0+. Uses MapControllers() and MapGet() etc. |
{id:int}) for clarity and validation.
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
// GET api/products
[HttpGet]
public IActionResult GetAllProducts()
{
return Ok(new string[] { "Product1", "Product2" });
}
// GET api/products/5
[HttpGet("{id}")]
public IActionResult GetProductById(int id)
{
return Ok($"Product with ID: {id}");
}
// POST api/products
[HttpPost]
public IActionResult CreateProduct([FromBody] Product product)
{
return CreatedAtAction(nameof(GetProductById), new { id = product.Id }, product);
}
}
[Route("api/[controller]")] sets a route prefix for the entire ProductsController. [controller] is replaced by the controller name ("Products").[HttpGet] matches a GET request to /api/products.[HttpGet("{id}")] matches a GET request to /api/products/5. The {id} is a route parameter passed to the method.[HttpPost] matches a POST request to /api/products.| Aspect | Attribute Routing | Convention-Based Routing |
|---|---|---|
| Configuration | Defined directly on controllers and action methods using attributes. | Defined centrally in the Program.cs file (or Startup.cs). |
| Control | Offers fine-grained control over URL patterns for each action. | Provides a centralized, predictable pattern for the entire application. |
| Readability | Keeps routing information close to the code that handles the request. | Requires referencing a separate configuration file. |
| Best suited for | RESTful Web APIs using HTTP verbs and resource-based URLs. | Traditional MVC apps using /{controller}/{action}/{id?} patterns. |
| Flexibility | Highly flexible for dynamic, complex URL patterns. | Can become difficult to manage for dynamic routing needs. |
The request pipeline in ASP.NET Core is a sequence of middleware components that process incoming HTTP requests and generate responses. Each component can inspect, modify, or short-circuit the request.
Middleware is added in Program.cs using methods like UseRouting(), UseAuthentication(), and UseEndpoints().
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
await next().
app.Use(async (context, next) =>
{
Console.WriteLine("Before next middleware");
await next.Invoke();
Console.WriteLine("After next middleware");
});
The order in which middleware is added affects how requests are processed. For example, UseAuthentication() must come before UseAuthorization().
The ASP.NET Core request pipeline is a flexible and powerful system built on middleware. It allows developers to control how requests are handled, responses are generated, and services are integrated.
| Filters in ASP.NET Core | Implementing JWT Authentication in ASP.NET Core | |