update introducery sessions notes
This commit is contained in:
@@ -1,125 +1,226 @@
|
||||
# Session 2: Middleware, Routing, and Controllers in ASP.NET Core MVC
|
||||
|
||||
## **0. Middleware and Request Pipeline**
|
||||
![[Pasted image 20241105101014.png]]
|
||||
![[Pasted image 20241105111037.png]]
|
||||
## 📝 Overview
|
||||
|
||||
![[Pasted image 20241105111022.png]]
|
||||
In this session, we’ll cover the following concepts:
|
||||
|
||||
## **1. Routing in ASP.NET Core MVC**
|
||||
- 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
|
||||
|
||||
Routing is a mechanism to map incoming HTTP requests to specific controller actions. Understanding routing is crucial for managing URL patterns and making your app user-friendly and SEO-optimized.
|
||||
## 📚 Topics Covered
|
||||
|
||||
### **Basic Routing Structure**
|
||||
### ✅ Middleware and Request Pipeline
|
||||
|
||||
Routes in ASP.NET Core are configured in `Program.cs` (or `Startup.cs` in earlier versions) using the `app.MapControllerRoute` method, which defines how URLs map to controllers and actions.
|
||||
> Visual understanding of the middleware flow and pipeline order
|
||||
> 🖼️ _See diagrams in original session notes_
|
||||
|
||||
### **Steps and Key Concepts in Routing**
|
||||
🔗 [ASP.NET Core Middleware Overview](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/)
|
||||
|
||||
1. **Define a Default Route** The default route defines the basic URL pattern that ASP.NET Core will follow.
|
||||
|
||||
```c#
|
||||
app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
|
||||
```
|
||||
- **Pattern**:
|
||||
- `{controller=Home}/{action=Index}/{id?}`:
|
||||
- `{controller=Home}`: Specifies the controller, defaulting to `Home`.
|
||||
- `{action=Index}`: Specifies the action method, defaulting to `Index`.
|
||||
- `{id?}`: Optional parameter for passing an `id`.
|
||||
1. **Attribute Routing** Define routes directly within the controller using attributes. This is useful when each action needs a unique route.
|
||||
|
||||
```c#
|
||||
[Route("products")]
|
||||
public class ProductsController : Controller
|
||||
{
|
||||
[HttpGet("all")]
|
||||
public IActionResult GetAllProducts() { /*...*/ }
|
||||
### ✅ Routing in ASP.NET Core
|
||||
|
||||
[HttpGet("{id}")]
|
||||
public IActionResult GetProductById(int id) { /*...*/ }
|
||||
}
|
||||
```
|
||||
1. **Custom Route Parameters and Constraints** You can add custom parameters and enforce constraints directly in the route to manage data types and URL patterns.
|
||||
|
||||
```c#
|
||||
app.MapControllerRoute(name: "custom", pattern: "{controller=Products}/{action=List}/{id:int:min(1)}");
|
||||
```
|
||||
> Learn how incoming requests map to controller actions through routing.
|
||||
> 🔗 [ASP.NET Core Routing Docs](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing)
|
||||
|
||||
- **Constraints**: `{id:int:min(1)}` ensures `id` is an integer greater than or equal to 1.
|
||||
- Other constraints include `bool`, `datetime`, `guid`, `minlength(x)`, `maxlength(x)`, and custom regular expressions.
|
||||
### ✅ Controllers
|
||||
|
||||
1. **Setting Default Actions Based on Controller** To give specific controllers a unique default action, create additional routes before the default route.
|
||||
|
||||
```c#
|
||||
app.MapControllerRoute(name: "gallery", pattern: "Gallery/{action=Main}/{id?}",defaults: new { controller = "Gallery" });
|
||||
> Understand how to structure controllers and handle requests with actions.
|
||||
> 🔗 [ASP.NET Core Controllers](https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/actions)
|
||||
|
||||
app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
|
||||
```
|
||||
|
||||
1. **SEO-Friendly and Readable URLs** For user-friendly URLs, use meaningful route names instead of parameters. This is particularly useful for e-commerce or content-heavy sites.
|
||||
```c#
|
||||
app.MapControllerRoute(name: "productDetail", pattern: "products/details/{id:int}/{name}");
|
||||
```
|
||||
## 📌 Notes
|
||||
|
||||
This structure allows URLs like `/products/details/10/laptop`, which is clear and keyword-rich.
|
||||
> _Collected from various sources including Microsoft Docs and ChatGPT_
|
||||
|
||||
---
|
||||
|
||||
## **2. Controllers in ASP.NET Core MVC**
|
||||
## 📍 Part 0: Middleware and Request Pipeline
|
||||
|
||||
Controllers are central in ASP.NET Core MVC and handle requests, retrieve data, and determine how it’s returned to the client.
|
||||
🖼️ **Diagrams**:
|
||||
|
||||
### **Controller Basics**
|
||||
- ![[Pasted image 20241105101014.png]]
|
||||
- ![[Pasted image 20241105111037.png]]
|
||||
- ![[Pasted image 20241105111022.png]]
|
||||
|
||||
- **Controller Naming**: Controllers usually end with "Controller" (e.g., `HomeController`, `ProductController`).
|
||||
- **Actions**: Methods within controllers are called action methods, typically returning a response to the user.
|
||||
---
|
||||
|
||||
### **Steps and Key Concepts in Controllers**
|
||||
## 📍 Part 1: Routing in ASP.NET Core MVC
|
||||
|
||||
1. **Creating a Basic Controller** A controller inherits from the `Controller` base class and contains action methods.
|
||||
|
||||
```c#
|
||||
public class HomeController : Controller
|
||||
{
|
||||
public IActionResult Index()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
}
|
||||
```
|
||||
Routing maps incoming HTTP requests to controller actions.
|
||||
|
||||
1. **Handling HTTP Methods with Attributes** Controllers use HTTP attributes like `[HttpGet]`, `[HttpPost]`, `[HttpPut]`, and `[HttpDelete]` to specify which HTTP methods they handle.
|
||||
|
||||
```c#
|
||||
[HttpPost]
|
||||
public IActionResult CreateProduct(Product product)
|
||||
{
|
||||
//Handle POST request
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
```
|
||||
|
||||
3. **Using Dependency Injection in Controllers** Dependency injection is commonly used in ASP.NET Core to inject services (like a repository) into controllers, supporting clean code and testability.
|
||||
|
||||
```c#
|
||||
public class ProductsController : Controller
|
||||
{
|
||||
private readonly IProductRepository _repository;
|
||||
public ProductsController(IProductRepository repository)
|
||||
{
|
||||
_repository = repository;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
### ✅ Basic Routing Structure
|
||||
|
||||
1. **Defining Action Parameters** Parameters passed to action methods are automatically bound from the URL or query string. Use model binding to parse complex objects from the request body.
|
||||
|
||||
|
||||
```c#
|
||||
public IActionResult EditProduct(int id, string name) {
|
||||
// Parameters are bound from the URL }
|
||||
```
|
||||
Routing is configured in `Program.cs` via `app.MapControllerRoute`.
|
||||
|
||||
````csharp
|
||||
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:
|
||||
|
||||
```csharp
|
||||
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:
|
||||
|
||||
```csharp
|
||||
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:
|
||||
|
||||
```csharp
|
||||
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
|
||||
|
||||
```csharp
|
||||
public class HomeController : Controller
|
||||
{
|
||||
public IActionResult Index()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### ✅ Handling HTTP Methods
|
||||
|
||||
Use attributes to define the HTTP method an action should handle:
|
||||
|
||||
```csharp
|
||||
[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:
|
||||
|
||||
```csharp
|
||||
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:
|
||||
|
||||
```csharp
|
||||
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](https://learn.microsoft.com/en-us/aspnet/core/)
|
||||
- ChatGPT 2025 sessions
|
||||
|
||||
Reference in New Issue
Block a user