ASP.NET Core: The MVC Request Life Cycle - p-patel/software-engineer-knowledge-base GitHub Wiki

https://app.pluralsight.com/courses/a6f34b5b-7124-4a5a-82e8-942f05305965/table-of-contents

Course Overview

  • How MVC features work and integrated together (e.g. middleware, routing)
  • Stepthrough MVC request lifecycle (request to response)
  • MVC technical details have changed significantly from ASP.NET

Introducing Essential Lifecycle Concepts

Introduction

Are You in the Right Place?

Need to Know:

  • MVC basics Nice to Know:
  • Legacy MVC request lifecycle Audience:
  • General .NET MVC developers looking to expand knowledge - e.g debugging
  • Developers adapted to MVC wanting to know what has changed in MVC Core

Defining the Request Lifecycle

  • Series of components, events or stages of an app that process a request or respond to user interaction

Understanding the Middleware Pipeline

Demo - Touring the Program and Startup Classes

Program class:

  • Configures and runs the web host
  • host configuration - content root, IIS integration and Kestral setup; configure Startup class (how the HTTP pipeline is setup)

Startup class:

  • ConfigureServices() - tied to dependency injection
  • Configure() - configure core HTTP pipeline by registering middleware components

Demo - Building a Simple Middlware Pipeline

  • Define own Configure() method with inline middleware components
app.Run(async context => 
{
  Debug.WriteLine("=== During Run ===);
  await context.Response.WriteAsync("The response from Run.");
});
  • Next add app.Use() call before above section to run before the above component and conditionally pass the request on if it can't handle it itself. On passing the request on to the next component the request can be handled before and after the next component with code before/after await next.Invoke()
  • Typically each middleware component provides some service such as authentication or caching.
  • Note there is also the Map() middleware method

Demo - Writing a Reusable Middleware Component

  • Create a new middleware class (uses conventions)
  • add public async Task Invoke(HttpContext context)
  • use app.Middleware<NewMiddlewareClass>()' to add middleware component to the pipeline in Startup.Configure()
  • Reuse middleware components across apps and abstract complex functionality into its own class

Demo - MVC Middleware Pipeline internals