.NET track

ASP.NET Core MVC Tutorial

Cross-platform web apps with middleware, DI, Razor, Entity Framework Core and Identity.

IntermediateExamples target .NET 9.
0/42 complete
Topics
42
Full lessons
42
Est. hours
~9
Interview Qs
27

Overview

ASP.NET Core is the modern, cross-platform, open-source web framework for .NET. ASP.NET Core MVC adds controllers and Razor views on top of its middleware pipeline.

Dependency injection, configuration and logging are built in. Apps run on Windows, Linux, Docker and cloud platforms such as Azure App Service.

What you will learn

  • Configure the app in Program.cs and the middleware pipeline
  • Build controllers, Razor views and view components
  • Use built-in dependency injection and configuration
  • Persist data with Entity Framework Core and secure it with Identity

Prerequisites

You will get the most from this track if you already know:

Learning path

The recommended sequence, from beginner to advanced. Each stage builds on the one before.

  1. 1Foundations · 7 topics · Beginner
    Introduction to ASP.NET Core MVC · ASP.NET Core Architecture · Project Creation · Program.cs · Middleware · Request Pipeline · Routing
  2. 2Controllers & Views · 5 topics · Beginner → Intermediate
    Controllers · Action Results · Razor Views · Layouts and Partial Views · View Components
  3. 3Models · 3 topics · Intermediate
    Model Binding · Model Validation · Data Annotations
  4. 4App Infrastructure · 5 topics · Intermediate
    Dependency Injection · Configuration · appsettings.json · Environment-Specific Settings · Logging
  5. 5Data Access · 9 topics · Intermediate
    Entity Framework Core · ADO.NET · SQL Server Integration · Database-First Approach · Code-First Approach · Migrations · CRUD Operations · Repository Pattern · Service Layer
  6. 6Security · 4 topics · Advanced
    Authentication · ASP.NET Core Identity · Authorization Policies · Session and Cookies
  7. 7Production · 9 topics · Advanced
    File Uploads · Caching · Exception Handling · Unit Testing · Performance Optimization · Security · IIS Deployment · Docker Deployment · Complete E-Commerce Project

Complete topic list

42 topics
1

Foundations

7 topics
  1. Introduction to ASP.NET Core MVCBeginner6m
  2. ASP.NET Core ArchitectureBeginner6m
  3. Project CreationBeginner6m
  4. Program.csBeginner5m
  5. MiddlewareBeginner6m
  6. Request PipelineBeginner6m
  7. RoutingBeginner6m
2

Controllers & Views

5 topics
  1. ControllersBeginner6m
  2. Action ResultsBeginner6m
  3. Razor ViewsBeginner6m
  4. Layouts and Partial ViewsBeginner6m
  5. View ComponentsIntermediate6m
3

Models

3 topics
  1. Model BindingIntermediate7m
  2. Model ValidationIntermediate7m
  3. Data AnnotationsIntermediate6m
4

App Infrastructure

5 topics
  1. Dependency InjectionIntermediate7m
  2. ConfigurationIntermediate6m
  3. appsettings.jsonIntermediate5m
  4. Environment-Specific SettingsIntermediate5m
  5. LoggingIntermediate6m
5

Data Access

9 topics
  1. Entity Framework CoreIntermediate7m
  2. ADO.NETIntermediate8m
  3. SQL Server IntegrationIntermediate6m
  4. Database-First ApproachIntermediate7m
  5. Code-First ApproachIntermediate6m
  6. MigrationsIntermediate6m
  7. CRUD OperationsIntermediate8m
  8. Repository PatternIntermediate7m
  9. Service LayerIntermediate7m
6

Security

4 topics
  1. AuthenticationAdvanced8m
  2. ASP.NET Core IdentityAdvanced6m
  3. Authorization PoliciesAdvanced7m
  4. Session and CookiesAdvanced7m
7

Production

9 topics
  1. File UploadsAdvanced7m
  2. CachingAdvanced6m
  3. Exception HandlingAdvanced7m
  4. Unit TestingAdvanced7m
  5. Performance OptimizationAdvanced7m
  6. SecurityAdvanced7m
  7. IIS DeploymentAdvanced6m
  8. Docker DeploymentAdvanced6m
  9. Complete E-Commerce ProjectAdvanced13m

Visual guides

2 diagrams

Code example

A taste of the track, from Introduction to ASP.NET Core MVC.

C#Program.cs Illustrative
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();                  // keep the demo output short
builder.Services.AddControllersWithViews();        // MVC = controllers + Razor views


var app = builder.Build();
app.MapDefaultControllerRoute();                   // {controller=Home}/{action=Index}/{id?}


app.Urls.Add("http://127.0.0.1:5101");
await app.StartAsync();


// Act like a browser: ask for the home page and print what comes back
using var http = new HttpClient { BaseAddress = new Uri("http://127.0.0.1:5101") };
var response = await http.GetAsync("/");
Console.WriteLine(
quot;
{(int)response.StatusCode} {response.Content.Headers.ContentType}");
Console.WriteLine((await response.Content.ReadAsStringAsync()).Trim()); await app.StopAsync(); // Models/StoreSummary.cs public record StoreSummary(string StoreName, int ProductCount); // Controllers/HomeController.cs using Microsoft.AspNetCore.Mvc; public class HomeController : Controller { public IActionResult Index() { var model = new StoreSummary("ShopSmart", 3); // the Model return View(model); // the View: Views/Home/Index.cshtml } } @* Views/Home/Index.cshtml *@ @model StoreSummary <h1>Welcome to @Model.StoreName</h1> <p>@Model.ProductCount products in stock</p>
Expected output
200 text/html; charset=utf-8
<h1>Welcome to ShopSmart</h1>
<p>3 products in stock</p>

Practice exercises

Show all 42 exercises
Routing

Add a route "blog/{year:int}/{month:int}/{slug}" handled by BlogController.Post(int year, int month, string slug), which returns the three values as text.

Controllers

Add a Search(string q) action to ProductsController that returns the matching products (name contains q, case-insensitive) to the Index view, or redirects to Index when q is empty.

Action Results

Add an action Export() that returns all product names as a text file products.txt, one per line.

Razor Views

Change the view so that items with a price above 1000 get the CSS class "premium" (and items in stock still have no class), and show the total number of items at the bottom.

Layouts and Partial Views

Add an optional section "Styles" to the layout’s <head>, and use it in the home page to add <link rel="stylesheet" href="/css/deals.css" />.

View Components

Write a CategoryMenuViewComponent that receives a list of category names from an ICategoryService and renders them as <nav><a>…</a></nav>.

Model Binding

Write an action Filter(ProductFilter filter) for GET /Search/Filter?Category=audio&MinPrice=500&Brands=sony&Brands=jbl where ProductFilter has Category, MinPrice (decimal?) and Brands (List<string>). Return the filter as JSON.

Model Validation

Add a ConfirmEmail field that must match Email, and a form-level error “Registrations are closed on Sundays” when DateTime.Today is a Sunday (shown with asp-validation-summary="ModelOnly").

Data Annotations

Write a [MaxWords(n)] attribute that fails when a string has more than n words, and use it on a review Title with n = 8.

Dependency Injection

Register an IEmailSender implementation called ConsoleEmailSender as transient and inject it into an AccountController whose Welcome(string to) action sends “Welcome to ShopSmart!”.

Configuration

Create PaymentOptions (Provider required, TimeoutSeconds between 5 and 60) bound from a "Payment" section with startup validation, and inject IOptions<PaymentOptions> into a CheckoutController that returns the provider name.

appsettings.json

Add an "Email" section with SmtpHost, Port and From to appsettings.json, bind it to EmailSettings with builder.Services.Configure<EmailSettings>(…), and print Port from IOptions<EmailSettings>.

Environment-Specific Settings

In a layout, load /lib/site.js in Development and https://cdn.shopsmart.example/site.min.js everywhere else, using the environment tag helper.

Logging

Add an appsettings.json Logging section that writes Debug logs for CheckoutService, Warning for Microsoft.AspNetCore, and Information for everything else.

Entity Framework Core

Write a query that returns each category name with its number of products and the average price, ordered by name.

ADO.NET

Add a DeleteAsync(int id) method that returns true when a product was deleted.

SQL Server Integration

Use AddDbContextPool instead of AddDbContext for better performance, with a pool size of 128.

Database-First Approach

Add a DisplayName property (“Name (Category)”) to the scaffolded Product without touching the generated file.

Code-First Approach

Add an Order entity with Id, OrderNumber (unique, max 20 chars), Total (precision 12,2) and PlacedAt (default SYSUTCDATETIME()), configured in an OrderConfiguration class.

Migrations

Write a migration by hand that renames the Products column Name to Title without losing data, with a Down method that reverses it.

CRUD Operations

Add a Details(int id) action and view that show the product name and price, returning 404 for unknown ids.

Repository Pattern

Add GetByNameAsync(string text) to IProductRepository (name contains text, case-insensitive in the fake) and implement it in both classes.

Service Layer

Write a CheckoutController.Buy(int productId, int quantity) action that calls OrderService and returns View("Confirmation", result) on success or puts result.Error in TempData and redirects to the product page on failure.

Authentication

Add an AccessDeniedPath "/Account/Denied" and an action that shows “You do not have access to this page.”, then protect an AdminController with [Authorize(Roles = "Admin")].

ASP.NET Core Identity

Seed an admin account at startup: create the Admin role if missing, create admin@shopsmart.example if missing, and add it to the role.

Authorization Policies

Make every page require a signed-in user by default with a fallback policy, and allow anonymous access to HomeController.Index.

Session and Cookies

Add a Remove(int id) action to CartController that decreases the quantity, removes the line at zero, and returns the remaining item count.

File Uploads

Add a Download(string name) action that returns an uploaded file only if name matches the pattern of 32 hex characters plus .png, preventing path traversal.

Caching

Output-cache a product page /Products/Details/{id} for 2 minutes, varying by the id route value, in a policy named "Product" tagged "products".

Exception Handling

Write an IExceptionHandler that handles OperationCanceledException (the user closed the page) by setting status 499 and returning true, so it is not logged as an error.

Unit Testing

Write a test that checks Details does not call the repository more than once and returns a ViewResult whose ViewName is null (the default view).

Performance Optimization

Enable response compression for HTTPS responses with Brotli and Gzip.

Security

Configure Content-Security-Policy-Report-Only instead of the enforced header, with a report-uri of /csp-reports, and add an endpoint that logs posted reports.

IIS Deployment

Write the PowerShell steps that deploy a new version with zero file-lock errors: create app_offline.htm, copy the publish folder, remove app_offline.htm.

Docker Deployment

Write a docker-compose.yml that runs ShopSmart (built from the Dockerfile) and SQL Server 2022, passes the connection string to the app, and starts the app after the database is healthy.

Complete E-Commerce Project

Make OrderService reject an order when a product in the cart no longer exists (deleted), returning “Some items are no longer available.”.

Common interview questions

Frequently asked questions

Is ASP.NET Core only for Windows?
No. It runs on Windows, Linux and macOS, and in Docker containers.