Asp.net MVC Request Life Cycle

Asp.net MVC Request Life Cycle

20 Jun 2024
Advanced
416K Views
8 min read

Asp.net MVC Request Life Cycle: An Overview

In this MVC Tutorial, I am going to expose the Asp.net MVC Request Life cycle. While programming with Asp.net MVC, you should be aware of the life of an Asp.net MVC request from birth to death. To understand MVC concepts from the scratch, enroll in our ASP.NET MVC Certification Training right now!

Read More: MVC Interview Questions and Answers

The steps of ASP.NET MVC Request Life Cycle

When you make a request to an Asp.net MVC web application. For more details refer Detailed ASP.NET MVC Pipeline.

    1.) Routing

    Asp.net Routing is the first step in the MVC request cycle. Basically, it is a pattern-matching system that matches the request’s URL against the registered URL patterns in the Route Table. When a matching pattern is found in the Route Table, the Routing engine forwards the request to the corresponding IRouteHandler for that request. The default one calls the MvcHandlerIf the patterns are not found in the Route Table, the routing engine returns a 404 HTTP status code against that request.

      1. When an application starts for the first time, it registers one or more patterns to the Route Table to tell the routing system what to do with any requests that match these patterns. An application has only one Route Table, which is set up in the application's Global.asax file.

        public static void RegisterRoutes(RouteCollection routes)
         { 
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
         routes.MapRoute( "Default", // Route name
         "{controller}/{action}/{id}", // URL with parameters
         new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
         ); 
        } 

        Read More: A Brief History of ASP.NET MVC Framework

      2. Routing

      2.) MvcHandler

      The MvcHandler is responsible for initiating the real processing inside ASP.NET MVC. MVC handler implements the IHttpHandler interface and further processes the request by using ProcessRequest method as shown below:

      1. protected internal virtual void ProcessRequest(HttpContextBase httpContext)
        {
         SecurityUtil.ProcessInApplicationTrust(delegate {
         IController controller;
         IControllerFactory factory;
         this.ProcessRequestInit(httpContext, out controller, out factory);
         try
         {
         controller.Execute(this.RequestContext);
         }
         finally
         {
         factory.ReleaseController(controller);
         }
         });
        }

        3.) Controller

        1. As shown in the above code, MvcHandler uses the IControllerFactory instance and tries to get an IController instance. If successful, the Execute method is called. The IControllerFactory could be the default controller factory or a custom factory initialized at the Application_Start event, as shown below:

          protected void Application_Start()
          {
           AreaRegistration.RegisterAllAreas();
           RegisterRoutes(RouteTable.Routes);
           ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());
          }

          4.) Action Execution

          Once the controller has been instantiated, the Controller's ActionInvoker determines which specific action to invoke on the controller. Action to be executed is chosen based on attributes ActionNameSelectorAttribute (by default method which has the same name as the action is chosen) and ActionMethodSelectorAttribute(If more than one method is found, the correct one is chosen with the help of this attribute).

          5.) View Result

          1. The action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The result types can be ViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult.

            6.) View Engine

            The first step in the execution of the View Result involves the selection of the appropriate View Engine to render the View Result. It is handled by IViewEnginean interface of the view engine. By default Asp.Net MVC uses WebForm and Razor view engines. You can also register your own custom view engine to your Asp.Net MVC application as shown below:

            1. protected void Application_Start() 
              { 
               //Remove All View Engine including Webform and Razor
               ViewEngines.Engines.Clear();
               //Register Your Custom View Engine
               ViewEngines.Engines.Add(new CustomViewEngine());
               //Other code is removed for clarity
              } 

              7.) View

              1. The action method may return a text string, a binary file, or JSON formatted data. The most important Action Result is the ViewResult, which renders and returns an HTML page to the browser using the current view engine.

              Summary

              I hope you will enjoy the Asp.Net MVC request life cycle while programming with Asp.Net MVC. I would like to have feedback from my blog readers. Your valuable feedback, questions, or comments about this article are always welcome. To delve deep into the core concepts of MVC, consider enrolling in our ASP.NET MVC Certification Course to get your hands on a comprehensive guide.

              Unlock the next level of MVC:

              FAQs

              The request is being taken from the User to the controller. -The Controller processes the request from the user and creates a data Model of that particular request. The data model that is being created is then passed to View which handles the frontend or the design.

              ASP.NET MVC Lifecycle
              The HTTP request is created and routed over to the application via a handler

              In ASP.NET MVC, the MVC life cycle can be defined as a step by step occurring events while processing a request and then generating its response.

              A request in ASP.NET MVC is processed like this:
              1. First, the requested URL is mapped by the routing system to a controller and action.
              2. The action method is executed to generate a result.
              3. The result is then passed onto the client.

              The different stages of the ASP.NET MVC request life cycle includes Routing, MVC Handler, Controller, Action Execution, View Result, View Engine and View.
              Share Article

              Live Classes Schedule

              Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
              ASP.NET Core Certification TrainingNov 08MON, TUE, WED, THU, FRI
              Filling Fast
              07:00AM to 08:30AM (IST)
              Get Details
              .NET Solution Architect Certification TrainingNov 09SAT, SUN
              Filling Fast
              05:30PM to 07:30PM (IST)
              Get Details
              ASP.NET Core Certification TrainingNov 10SAT, SUN
              Filling Fast
              10:00AM to 12:00PM (IST)
              Get Details
              .NET Solution Architect Certification TrainingNov 24SAT, SUN
              Filling Fast
              10:00AM to 12:00PM (IST)
              Get Details

              Can't find convenient schedule? Let us know

              About Author
              Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

              Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
              Accept cookies & close this