NET Centric ComputingUnit 210 min read

ASP.NET Core: Architecture, Features, and Setup

Unit 2 of NET Centric Computing introduces ASP.NET Core, its architecture, core features, and hands-on setup, including comparisons with traditional ASP.NET, IDEs (Visual Studio, VS Code), and project templates. Students learn to create a basic "Hello World" app and understand its file structure.

TAKEAWAYS:

  • Understand ASP.NET Core’s cross-platform architecture and its separation from the legacy ASP.NET Framework.
  • Compare ASP.NET Core with ASP.NET using a feature matrix (performance, dependencies, and tooling).
  • Learn the project structure of an ASP.NET Core MVC app and the role of Program.cs, Startup.cs, and Controllers.
  • Set up a development environment using Visual Studio or VS Code and create a minimal "Hello World" app.
  • Recognize NuGet packages and how they extend ASP.NET Core functionality.
  • Apply ASP.NET Core in real-world scenarios like eSewa’s payment gateway or Khalti’s API integrations.

What is ASP.NET Core?

ASP.NET Core is a modern, cross-platform, high-performance framework for building web applications, APIs, and microservices. Developed by Microsoft, it is the successor to ASP.NET MVC and ASP.NET Web Forms, offering significant improvements in performance, scalability, and flexibility.

Key Features of ASP.NET Core

mindmap
  root((ASP.NET Core))
    Features
      Cross-Platform: Runs on Windows, Linux, macOS
      High Performance: Optimized for speed (Kestrel web server)
      Modular: Use only what you need (NuGet packages)
      Cloud-Ready: Designed for Docker and Kubernetes
      Dependency Injection: Built-in DI container
      Razor Pages: Simplified page-focused development
      Blazor: Full-stack C# web apps

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 HTTP server) Slower (IIS-dependent)
Dependencies Lightweight (no GAC) Heavy (GAC, Windows-specific)
Tooling Visual Studio, VS Code, CLI Visual Studio (limited to Windows)
Hosting Self-hosted (Kestrel) or IIS IIS-only
Updates Frequent, modular Slow, monolithic

Architecture of ASP.NET Core

ASP.NET Core follows a modular, component-based architecture, allowing developers to include only the libraries they need. The core components include:

  1. Kestrel: A lightweight, cross-platform web server (can be paired with IIS/NGINX for production).
  2. Razor: A view engine for dynamic web pages.
  3. Entity Framework Core: A modern ORM for database interactions.
  4. Middleware Pipeline: A request-processing pipeline (e.g., authentication, logging, routing).
  5. Dependency Injection (DI): Built-in support for DI containers.

How the Middleware Pipeline Works

sequenceDiagram
    participant Client
    participant Kestrel
    participant Middleware1
    participant Middleware2
    participant Controller
    participant View

    Client->>Kestrel: HTTP Request
    Kestrel->>Middleware1: Invoke()
    Middleware1->>Middleware2: Invoke()
    Middleware2->>Controller: Handle Request
    Controller-->>Middleware2: Return Response
    Middleware2-->>Middleware1: Pass Through
    Middleware1-->>Kestrel: Finalize Response
    Kestrel-->>Client: HTTP Response

Setting Up ASP.NET Core

Prerequisites

  • .NET SDK: Download from dotnet.microsoft.com.
  • IDE: Visual Studio (Windows/macOS) or VS Code (cross-platform).
  • Code Editor: VS Code with C# extensions (recommended for lightweight development).

Creating a "Hello World" App

  1. Install the .NET SDK and verify:
    dotnet --version
    
  2. Create a new project:
    dotnet new mvc -n HelloWorldApp
    cd HelloWorldApp
    
  3. Run the app:
    dotnet run
    
    • The app starts at https://localhost:5001 (or http://localhost:5000).
    • Open Controllers/HomeController.cs to see the default Index() method.

Project Structure in ASP.NET Core MVC

A typical ASP.NET Core MVC project has the following key files/folders:

File/Folder Purpose
Program.cs Entry point (configures middleware pipeline and services).
appsettings.json Configuration settings (connection strings, API keys).
Controllers/ Contains MVC controllers (e.g., HomeController.cs).
Views/ Razor views (.cshtml files for UI).
Models/ Business logic and data models (e.g., User.cs).
wwwroot/ Static files (CSS, JS, images).
Startup.cs (Legacy) Configured services and middleware (deprecated in .NET 6+).

Example: Program.cs in .NET 6+

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

NuGet Packages in ASP.NET Core

NuGet is a package manager for .NET. Common packages include:

  • Microsoft.EntityFrameworkCore: For database operations.
  • Microsoft.AspNetCore.Identity: For user authentication.
  • Newtonsoft.Json: For JSON serialization.
  • AutoMapper: For object-to-object mapping.

Adding a NuGet Package:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

In the Real World

  1. eSewa (Nepal):

    • Uses ASP.NET Core for its payment gateway API to handle secure transactions between users and banks.
    • How it applies: The middleware pipeline validates requests, while Entity Framework Core manages database transactions for payment records.
  2. Khalti (Nepal):

    • Built with ASP.NET Core for its merchant API, enabling businesses to accept digital payments.
    • How it applies: The modular architecture allows Khalti to scale during festivals (e.g., Dashain, Tihar) when transaction volumes spike.
  3. Daraz (Alibaba Group):

    • Uses ASP.NET Core for its order processing microservices, ensuring low-latency responses during sales events.
    • How it applies: The Kestrel server handles thousands of concurrent requests during flash sales, while Razor Pages render dynamic product pages.
  4. Ncell’s Customer Portal:

    • Leverages ASP.NET Core for its billing and recharge system, integrating with SMS gateways for notifications.
    • How it applies: The DI container manages dependencies like SMS providers and database connections cleanly.

Worked Example: NTC’s Traffic Route Optimization

  • Scenario: The Nepal Telecommunications Company (NTC) wants to optimize its fiber-optic route planning for new towers.
  • Solution: An ASP.NET Core web API is built to:
    1. Use Entity Framework Core to query geographic data (stored in SQL Server).
    2. Apply middleware to validate tower locations against terrain rules.
    3. Return optimized routes via JSON responses to field engineers.
  • Code Snippet (Controller):
    [ApiController]
    [Route("api/[controller]")]
    public class RouteOptimizerController : ControllerBase
    {
        private readonly AppDbContext _context;
        public RouteOptimizerController(AppDbContext context) => _context = context;
    
        [HttpGet("optimize")]
        public IActionResult OptimizeRoutes([FromQuery] decimal startLat, [FromQuery] decimal startLong)
        {
            var routes = _context.TerrainData.GetOptimizedPath(startLat, startLong);
            return Ok(routes);
        }
    }
    

Advantages and Disadvantages of ASP.NET Core

Advantages Disadvantages
Cross-platform (Windows/Linux/macOS) Steeper learning curve for beginners.
High performance (Kestrel server) Requires manual configuration for some features.
Modular (use only what you need) Smaller community than PHP/Node.js for some niches.
Strong typing and C# features Migration from ASP.NET Framework can be complex.
Integrated tooling (VS, VS Code, CLI) Some legacy libraries are not ported.

Exam Tip

  1. Focus on Architecture:

    • Expect questions on middleware pipeline, Kestrel vs. IIS, and dependency injection.
    • Example Question: "Explain how a request flows through the ASP.NET Core middleware pipeline. Draw a sequence diagram."
  2. Project Structure:

    • Memorize the roles of Program.cs, Controllers, and Views.
    • Example Question: "List the key files in an ASP.NET Core MVC project and describe the purpose of appsettings.json."
  3. Real-World Applications:

    • Link concepts to eSewa’s API, Khalti’s scalability, or NTC’s route optimization.
    • Example Question: "How would you use ASP.NET Core to build a payment gateway like eSewa? Discuss middleware and database layers."
  4. NuGet Packages:

    • Know how to add packages via CLI or Visual Studio.
    • Example Question: "What NuGet package would you use for database operations in ASP.NET Core? Write the CLI command to install it."
  5. Comparisons:

    • Be ready to compare ASP.NET Core vs. ASP.NET Framework in a table.
    • Example Question: "Why is ASP.NET Core preferred over ASP.NET Framework for cloud deployments?"

Visual Summary for Quick Revision

graph TD
    A["ASP.NET Core"] --> B["Cross-Platform"]
    A --> C["Modular Architecture"]
    A --> D["Middleware Pipeline"]
    A --> E["Kestrel Server"]
    A --> F["NuGet Packages"]
    B --> G["Windows/Linux/macOS"]
    C --> H["Use Only Required Libraries"]
    D --> I["Request Processing Flow"]
    E --> J["High Performance"]
    F --> K["EntityFrameworkCore, Newtonsoft.Json"]

Based on the TU BIT syllabus for NET Centric Computing (BIT351), unit 2.

Discussion

Loading…