Session 2: Middleware, Routing, and Controllers in ASP.NET Core MVC
๐ Overview
In this session, weโll cover the following concepts:
- Middleware and the ASP.NET Core request pipeline
- Routing structure: default, attribute-based, constraints, SEO-friendly
- Creating and structuring controllers
- Handling HTTP methods
- Dependency Injection in controllers
- Model binding and action parameters
๐ Topics Covered
โ Middleware and Request Pipeline
Visual understanding of the middleware flow and pipeline order
๐ผ๏ธ See diagrams in original session notes
๐ ASP.NET Core Middleware Overview
โ Routing in ASP.NET Core
Learn how incoming requests map to controller actions through routing.
๐ ASP.NET Core Routing Docs
โ Controllers
Understand how to structure controllers and handle requests with actions.
๐ ASP.NET Core Controllers
๐ Notes
Collected from various sources including Microsoft Docs and ChatGPT
๐ Part 0: Middleware and Request Pipeline
๐ผ๏ธ Diagrams:
- [](../../../Assets/Pasted image 20241105101014.png)
- [](../../../Assets/Pasted image 20241105111037.png)
- [](../../../Assets/Pasted image 20241105111022.png)
๐ Part 1: Routing in ASP.NET Core MVC
Routing maps incoming HTTP requests to controller actions.
โ Basic Routing Structure
Routing is configured in Program.cs
via app.MapControllerRoute
.
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
- `{controller=Home}`: default controller
- `{action=Index}`: default action
- `{id?}`: optional URL parameter
---
### โ
Attribute Routing
Define routes directly in the controller using attributes:
```csharp
[Route("products")]
public class ProductsController : Controller
{
[HttpGet("all")]
public IActionResult GetAllProducts() { /*...*/ }
[HttpGet("{id}")]
public IActionResult GetProductById(int id) { /*...*/ }
}
โ Route Parameters & Constraints
You can enforce patterns and types using constraints:
app.MapControllerRoute(
name: "custom",
pattern: "{controller=Products}/{action=List}/{id:int:min(1)}"
);
int:min(1)
meansid
must be an integer โฅ 1- Other constraints:
bool
,datetime
,guid
,minlength(x)
, etc.
โ Per-Controller Default Routes
You can assign a default action to a specific controller:
app.MapControllerRoute(
name: "gallery",
pattern: "Gallery/{action=Main}/{id?}",
defaults: new { controller = "Gallery" }
);
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
โ SEO-Friendly URLs
Use descriptive URLs for readability and SEO:
app.MapControllerRoute(
name: "productDetail",
pattern: "products/details/{id:int}/{name}"
);
โ
Example output: /products/details/10/laptop
๐ Part 2: Controllers in ASP.NET Core MVC
Controllers handle requests and return responses, acting as a bridge between models and views.
โ Creating a Basic Controller
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
โ Handling HTTP Methods
Use attributes to define the HTTP method an action should handle:
[HttpPost]
public IActionResult CreateProduct(Product product)
{
return RedirectToAction("Index");
}
Other attributes include:
[HttpGet]
[HttpPut]
[HttpDelete]
โ Dependency Injection in Controllers
Inject services like repositories into controllers for better separation of concerns:
public class ProductsController : Controller
{
private readonly IProductRepository _repository;
public ProductsController(IProductRepository repository)
{
_repository = repository;
}
}
โ Action Parameters and Model Binding
Parameters are bound automatically from the URL, query string, or form body:
public IActionResult EditProduct(int id, string name)
{
// id and name are bound from query or route
}
For complex types, ASP.NET Core binds data from the request body (e.g., forms or JSON).
๐งช Practice
- Define multiple routes with custom constraints
- Build an SEO-friendly route pattern
- Create controller with basic actions (
Index
,Details
,Create
) - Add attribute-based routes to actions
- Use
[HttpGet]
,[HttpPost]
on appropriate methods - Inject a service into a controller via constructor
- Bind parameters from query and route
๐ Acknowledgments
Sources:
- Microsoft Docs
- ChatGPT 2025 sessions