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) means id 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: