The MVC Request Life Cycle - p-patel/software-engineer-knowledge-base GitHub Wiki

https://app.pluralsight.com/courses/1e5d33f3-1602-4c78-8577-9ec05468bd86/table-of-contents

Overview

Introduction

  • Covers the request lifecycle through ASP.NET and ASP.NET MVC which provides a modular framework where the default behaviour can be overriden when appropriate

Who Is This Course For?

  • Already familiar with MVC
  • Covers concepts over code
  • For developers looking for a deeper understanding of MVC
  • For developers never exposed to the larger ASP.NET platform

The Application and Request Life Cycle Events

Introduction

  • Lifecycle discussion involves HttpHandlers and HttpModules
  • What happens when the application first receives a request
  • Initial application configuration (inc. configuration before the applications starts)
  • Request lifecycle events that fire every time a request is processed + how MVC plugs into this pipeline
  • Tapping into lifecycle events using custom code

Understanding Application Start And End Events

  • MVCApplication class in Global.asax, heart of MVC application
  • Inherits from HttpApplication class which exposes lifecycle events which handlers can be attached for e.g.:
  • BeginRequest
  • ResolveRequestCache (Routing occurs here based on defined routing table)
  • MapRequestHandler
  • AcquireRequestState
  • RequestHandlerExecute
  • UpdateRequestCache
  • LogRequest
  • EndRequest also
  • ApplicationStart
  • ApplicationEnd these 2 events occur before/after any other event and also allow the application to stop receiving requests

Application Start method:

  • brings application to life

  • fires when the first request is received

  • enables global configuration before anything else happens

  • example configuration: register areas, global filters, script/css bundles, routes for URL routing module

  • Registering Routes:

  • Each route requires a RouteHandler class which provides a HttpHandler which will process the incoming request

  • Application End method:

  • fires when application stops and then no more requests can be received

  • for tasks before an application shutdowns

  • not used very often (as it only fires when application is shut down expectedly)

Demo - Applicaion Start and End

  • Application_Start() \ Application_End() methods
  • Application_Start contains RouteConfig.RegisterRoutes()
  • Remember MVC is open-source

Configurations with the PreApplicationStart method

  • Another option for running intial config code
  • Applied through an attribute that defines a type and method on the type to run
  • Often used to register Http modules (Http modules often register to .NET lifecycle events so registering them before anything else ensures they have access to all events that follow)