NET Centric ComputingUnit 212 min read
ASP.NET Core Architecture & MVC Pattern: Core Concepts & Real-World Use
Unit 2 of NET Centric Computing covers ASP.NET Core’s modular architecture, the MVC design pattern, and how they enable scalable web apps. Learn the three-layer separation (Model-View-Controller), middleware pipeline, dependency injection, and cross-cutting concerns—with comparisons to traditional ASP.NET, real-world e
Core Concepts: ASP.NET Core Architecture
1. Modular and Cross-Platform Design
ASP.NET Core is a revolutionary rewrite of ASP.NET (originally for Windows-only IIS). It is:
- Cross-platform: Runs on Windows, Linux, and macOS.
- Modular: Only include what you need (e.g., no
System.Webdependency). - High-performance: Built on .NET Core runtime (not the full .NET Framework).
Why does this matter? Traditional ASP.NET was tightly coupled to IIS and Windows. ASP.NET Core breaks free, allowing deployment on cloud servers (Azure, AWS) or even Raspberry Pi clusters.
2. The Middleware Pipeline
ASP.NET Core uses a pipeline of middleware components that process HTTP requests sequentially. Each middleware can:
- Modify the request/response.
- Short-circuit the pipeline (e.g., return a 404).
- Pass control to the next middleware.
Example Pipeline (from top to bottom):
- Request Decompression (if compressed)
- Routing (matches URLs to endpoints)
- Authentication (checks JWT/OAuth tokens)
- Authorization (checks user permissions)
- Exception Handling (logs errors)
- Static Files (serves
wwwrootfiles) - MVC/Minimal APIs (processes the request)
- Response Compression (gzip/deflate)
Mermaid Diagram: Middleware Pipeline Flow
flowchart LR
A["HTTP Request"] --> B["Middleware 1\n(Decompression)"]
B --> C["Middleware 2\n(Routing)"]
C --> D["Middleware 3\n(Authentication)"]
D --> E["Middleware 4\n(Authorization)"]
E --> F["Middleware 5\n(Exception Handling)"]
F --> G["Middleware 6\n(Static Files)"]
G --> H["Middleware 7\n(MVC/Minimal API)"]
H --> I["HTTP Response"]Real-World Tie-In:
- eSewa’s Login Flow: When you log in, the pipeline first checks your JWT token (Authentication middleware), then verifies your role (Authorization middleware) before processing your payment request. If any step fails (e.g., expired token), the pipeline short-circuits and returns an error.
3. Dependency Injection (DI) and Inversion of Control (IoC)
ASP.NET Core automatically configures DI, allowing you to:
- Decouple components (e.g., a
UserServicedoesn’t need to create its ownDatabaseContext). - Replace implementations easily (e.g., swap
SqlDatabaseforMockDatabasein tests). - Use built-in services (logging, caching, configuration).
Example: Registering a Service
// Program.cs
builder.Services.AddScoped<IUserRepository, UserRepository>();
// Now, any controller can inject IUserRepository via constructor.
Why Scoped?
- Transient: New instance per request (e.g.,
HttpContext). - Scoped: One instance per HTTP request (e.g.,
DbContext). - Singleton: One instance for the app lifetime (e.g.,
ILogger).
The MVC Pattern: Separation of Concerns
1. Model-View-Controller: Three-Layer Architecture
| Component | Role | Example in a Library App |
|---|---|---|
| Model | Business logic/data (e.g., Book, User). |
Book class with Title, Author, IsAvailable. |
| View | UI (Razor, HTML, or SPA like React). | Index.cshtml showing a list of books. |
| Controller | Handles HTTP requests, updates Model, returns View. | BooksController with Index(), Details(int id). |
Key Principle:
- No business logic in Views (e.g., no SQL queries in
.cshtml). - No UI code in Models (e.g.,
Bookclass doesn’t know it’s displayed in a table).
Mermaid Diagram: MVC Request Flow
sequenceDiagram
User->>+Controller: GET /Books
Controller->>+Model: FetchAllBooks()
Model-->>-Controller: List<Book>
Controller->>+View: Render(books)
View-->>-User: HTML Page2. How MVC Handles a Request (Step-by-Step)
Let’s trace a request to /Books/Details/5 in a Library Management System:
Routing:
- The URL
/Books/Details/5is matched toBooksController.Details(5)via attribute routing or conventional routing.[Route("Books/Details/{id}")] public IActionResult Details(int id) { ... }
- The URL
Controller Action:
- The
Detailsmethod fetchesBookwithid = 5from the Model (BookRepository).public IActionResult Details(int id) { var book = _bookRepository.GetById(id); return View(book); // Passes data to the View }
- The
View Rendering:
- The
Details.cshtmlRazor view receives thebookobject and renders it as HTML.@model Library.Models.Book <h1>@Model.Title</h1> <p>Author: @Model.Author</p>
- The
Response:
- The HTML is sent back to the user.
Real-World Tie-In:
- Daraz’s Product Page:
When you click a product (e.g.,
/electronics/smartphone/123), Daraz’s MVC backend:- Routes to
ProductsController.Details(123). - Fetches product data from the database (Model).
- Renders the product page (View) with images, price, and "Add to Cart" button.
- Routes to
3. Advantages of MVC
| Advantage | Explanation | Example |
|---|---|---|
| Separation of Concerns | Changes to UI (View) don’t break business logic (Model). | Update Details.cshtml without touching Book class. |
| Testability | Models and Controllers can be unit-tested without a browser. | Mock IBookRepository to test Details(). |
| Reusability | Models/Views can be reused across projects. | Same User model in Library and E-Commerce apps. |
| Scalability | Large teams can work on Views, Models, or Controllers independently. | Frontend team updates UI; backend team adds features. |
| SEO-Friendly URLs | Clean URLs (e.g., /books/harry-potter) instead of ?id=123. |
Google ranks MVC apps better than SPA-only apps. |
Disadvantage:
- Slightly more boilerplate than Minimal APIs (e.g., defining
Controllerclasses). - Not ideal for SPAs (Single Page Apps like React/Angular), where most logic runs client-side.
ASP.NET Core vs. Traditional ASP.NET
| Feature | ASP.NET Core | Traditional ASP.NET (Framework) |
|---|---|---|
| Platform | Cross-platform (Windows/Linux/macOS). | Windows-only. |
| Performance | Faster (Kestrel web server, optimized runtime). | Slower (IIS-dependent). |
| Dependency Model | Modular (only include what you need). | Monolithic (System.Web required). |
| Hosting | Self-hosted (Kestrel) or IIS. | IIS-only. |
| Configuration | JSON/YAML/environment variables. | web.config. |
| DI/IoC | Built-in, flexible. | Requires third-party libraries (e.g., Unity). |
| Deployment | Single executable (dotnet publish). |
Multiple DLLs + bin folder. |
Key Takeaway:
- Use ASP.NET Core for new projects (cloud, Linux, microservices).
- Legacy ASP.NET is still used for old Windows apps but is not future-proof.
In the Real World
1. eSewa: Authentication and Authorization
- Idea Used: Middleware Pipeline + ASP.NET Core Identity.
- How:
- When you log in, eSewa’s middleware checks your JWT token (Authentication).
- If valid, it grants access to payment endpoints (Authorization).
- If the token is missing/expired, the pipeline short-circuits and returns a login redirect.
- Code Snippet (Simplified):
// Middleware to validate JWT app.UseAuthentication(); app.UseAuthorization(); // Only authenticated users can access /Pay [Authorize] [Route("Pay")] public class PayController : Controller { ... }
2. Daraz: Caching and Performance
- Idea Used: Response Caching Middleware.
- How:
- Daraz caches product listings (e.g.,
/electronics) for 5 minutes to reduce database load. - Uses
IMemoryCacheorIDistributedCache(Redis) for shared caching.
- Daraz caches product listings (e.g.,
- Example:
// Enable caching for product listings builder.Services.AddMemoryCache(); app.UseResponseCaching(); [ResponseCache(Duration = 300)] // Cache for 5 minutes public IActionResult Electronics() { ... }
3. Ncell’s Billing Portal: MVC for Complex Workflows
- Idea Used: MVC Pattern for Multi-Step Processes.
- How:
- Model:
Bill,User,Paymententities. - Controller:
BillingControllerwith actions likeGenerateBill(),ProcessPayment(). - View: Razor pages for each step (e.g.,
PaymentConfirmation.cshtml).
- Model:
- Why MVC?
- Separates bill generation logic (Model) from the UI (View).
- Easy to add new payment methods (e.g., Khalti, ESEWA) without changing the View.
Exam Tip: How This Unit is Tested
Common Question Types
Define and Compare:
- "Explain the MVC pattern with a diagram." → Draw the MVC flow (Mermaid above) and label Model/View/Controller.
- "Differentiate ASP.NET Core and traditional ASP.NET." → Use the comparison table above.
Short Answers (5 marks):
- "What is middleware in ASP.NET Core?"
Answer: A pipeline of components that process HTTP requests/responses sequentially (e.g., Authentication, Routing). Each middleware can modify or short-circuit the pipeline.
- "Why use Dependency Injection?"
Answer: To decouple components, improve testability, and enable runtime swapping of implementations (e.g.,
ILogger).
- "What is middleware in ASP.NET Core?"
Worked Examples (10–15 marks):
- "Trace the flow of a request to
/Books/5in MVC."Answer: Use the MVC sequence diagram and explain each step (Routing → Controller → Model → View).
- "Design a middleware to log requests."
Answer:
app.Use(async (context, next) => { Console.WriteLine($"Request: {context.Request.Path}"); await next(); });
- "Trace the flow of a request to
Real-World Applications (5–10 marks):
- "How does Daraz use ASP.NET Core’s caching?"
Answer: Uses
ResponseCacheorIDistributedCacheto store product listings, reducing database load and improving response time.
- "How does Daraz use ASP.NET Core’s caching?"
Marks Distribution
| Component | Marks | What to Include |
|---|---|---|
| Definition | 2–3 | Clear, concise (e.g., "MVC separates Model, View, Controller..."). |
| Diagram | 2–3 | Mermaid/MVC flow or labelled architecture. |
| Code Example | 3–5 | Minimal but complete (e.g., [Authorize] attribute). |
| Real-World Tie-In | 2–3 | Name a Nepali app (eSewa, Daraz) and explain one idea. |
| Comparison Table | 3–5 | ASP.NET Core vs. Framework (use the table above). |
Common Pitfalls
- Forgetting the Pipeline Order: Middleware runs top to bottom. Exception handling must come before MVC.
- Mixing Model and View Logic: Never write SQL queries in
.cshtml! - Ignoring DI: Always inject dependencies via constructor, not
new.
Final Checklist Before Exam:
✅ Can you draw the MVC flow from memory?
✅ Do you know the order of middleware (e.g., Auth before MVC)?
✅ Can you write a basic controller action with [Route] and [Authorize]?
✅ Can you explain one real-world app (eSewa/Daraz) using this unit’s concepts?
Based on the TU BSc CSIT syllabus for NET Centric Computing (CSC367), unit 2.
Discussion
Loading…