ASP.NET Core MVC Request Life Cycle

ASP.NET Core MVC Request Life Cycle

In this article, I am going to discuss the ASP.NET Core MVC Request Life Cycle in detail. In the ASP.NET Core MVC application, when a client makes a request, that request goes through various stages before returning the response to the client. The various stages the request goes through are nothing but the ASP.NET Core MVC Request Life Cycle, or you can also say that ASP.NET Core MVC Request Pipeline. So, if you are working as an ASP.NET Core MVC Developer, then you should be aware of the ASP.NET Core MVC Request Life Cycle, i.e., from birth to death of a request. 

So, in short, we can say that the ASP.NET Core MVC Request Life Cycle is a sequence of events, stages, or components that interact with each other to process an HTTP request and generate an HTTP response that goes back to the client who initially made the request. The client is nothing but your web browser from where you access the website.

Example to Understand ASP.NET Core MVC Request Life Cycle:

Let us first create an ASP.NET Core Application using the Model-View-Controller Project template to understand the ASP.NET Core MVC Request Life Cycle.

To create an ASP.NET Core Web Application with the MVC Project template. First of all, open Visual Studio 2022 and then click on the Create a new project tab as shown in the below image.

ASP.NET Core Web Application with the MVC Project template

Once you click on the Create a new Project tab, it will open the following Create a new Project window. From this window, select C#, All Platforms, and Web from respective dropdowns as highlighted below. Select ASP.NET Core Web App (Model-View-Controller) as highlighted below, and click the Next button as shown in the image below.

ASP.NET Core Web App (Model-View-Controller)

Once you click on the Next button, it will open the Configure Your New Project window. Here, you need to provide the necessary information to create a new ASP.NET Core project. First, give an appropriate name for your project (MVCRequestLifeCycle), set the location where you want to create this project, and the solution name for the ASP.NET Core Web application. And finally, click on the Create button, as shown in the image below.

Configure Your New Project

Once you click on the Next button, it will open the following Additional Information window. Here, you need to select “Framework” – “.NET 6.0 (Long-term support)”, “Authentication type” – “None”. You also need to check the Configure for HTTPS and Do not use top-level statements check boxes, and finally, click on the Create button as shown in the image below.

Example to Understand ASP.NET Core MVC Request Life Cycle

That’s it. Once you click on the Create Button, the project is going to be created with the Model-View-Controller, i.e., MVC template with the following folder and file structure.

Example to Understand ASP.NET Core MVC Request Life Cycle

MVC Setup in ASP.NET Core Web Application:

As we created the above ASP.NET Core Web Application using the Model-View-Controller Template, by default, the required MVC Services and Middleware components are included in the Main method of the Program class. To confirm this, open the Program.cs class file and verify the same as follows.

namespace MVCRequestLifeCycle
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add MVC Services to the container.
            builder.Services.AddControllersWithViews();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            //Configuring End Points for controller action methods
            app.MapControllerRoute(
                name: "default",
                //Default Controller Name = Home
                //Default Action Method Name = Index
                //ID is an Optinal Parameter as it is Declared using ? which makes it a Nullable Type
                pattern: "{controller=Home}/{action=Index}/{id?}");

            app.Run();
        }
    }
}
Running MVC Application:

The ASP.NET Core Web APP (Model-View-Controller) Project template creates the Home Controller with some views. Let us run the application and see the output as shown below.

Running MVC Application

When the application is launched, the URL would be only https://localhost:7200/, but passing https://localhost:7200/Home/Index/1 also loads the same page as shown in the below image.

Running ASP.NET Core MVC Application

As highlighted in the above image, https://localhost:7200/Home/Index/1 is the HTTP Request. The request has “Home/Index/1”. If you look at the Main method of the Program class, then you will see the routing pattern as “pattern: “{controller=Home}/{action=Index}/{id?}”);” as shown in the below image.

Default Routing ASP.NET Core MVC Web Application

So, the .NET Core tries to map the request using the routing pattern

Request: Home/Index/1

Routing pattern: {Controller}/{Action}/{Id}

From this pattern matching, the .NET core framework understands that the request needs to be routed to the Home Controller and Index Action Method, and the optional parameter to the action method ID is 1.

Next, the Controller Initialization happens (i.e., creating and initializing the Home Controller Class by .NET Framework using Reflection) and invoked the Index Action method by passing the optional Id parameter. After that, the action method is going to be executed. In the default code of the Home Controller class, the Index action method does not expect the Id parameter, so the optional Id parameter will be ignored in this case. So, if you open the HomeController class, you will see the following Index Action method.

ASP.NET Core MVC Request Life Cycle

The index action method returns a “View Result” object (View () returns a “View Result” object). The .NET Core follows the naming convention and looks for the Index view. Then, it renders the Index view as the HTTP Response to the Client who initially made the request.

Note: Passing only “https://localhost:7200/” also loads the Index page within the Home Controller. This is because the defaults are mentioned in the routing pattern itself. Home is the default Controller, and Index is the default action method. If Controller and action names are not provided in the request, then it will take the default values. Now, let us proceed and understand the ASP.NET Core MVC Request Life Cycle.

ASP.NET Core MVC Request Life Cycle:

For a better understanding of the ASP.NET Core MVC Request Life Cycle, please have a look at the following diagram.

ASP.NET Core MVC Request Life Cycle

The above block diagram shows the complete life cycle of the ASP.NET Core MVC Request. As you can see, the life cycle is composed of many stages. Let us understand the Role and Responsibility of each stage in the ASP.NET Core MVC Request Life Cycle.

Middleware: Middleware is the basic building block of the HTTP request pipeline. Request enters the request pipeline through middleware. In ASP.NET Core Web Application, these are a series of components combined to form a request pipeline to handle any incoming HTTP request.

Routing: Routing is a middleware component that implements the MVC framework in ASP.NET Core Web Application. When a request is received, the ASP.NET Routing system matches the incoming URL to a route pattern defined in the application’s route configuration. This determines which controller and action method should handle the request with the help of convention and attribute routing.

Controller Initialization: At this stage, the process of initialization and execution of controllers takes place. Once the routing system determines the appropriate controller and action method, an instance of the controller is created (.NET Framework uses the Reflection concept to create an instance of the controller class). The controller’s constructor and any dependencies are resolved using the configured dependency injection container.

Action Method Execution: The action method specified in the route is invoked on the controller instance. The action method performs the necessary logic to generate the response. As part of the action method, the following things are going to happen.

  1. Model Binding: The model binding process takes place before the action method is executed. The framework maps the values from the request (e.g., query strings, form data, route parameters) to the action method’s parameters or model properties.
  2. Action Filters: Action filters can be applied to the action method or the controller to perform pre-and-post-processing logic. These filters can modify the request and perform authentication, authorization, logging, caching, etc.

Result Execution: The action method returns an instance of an ActionResult or one of its derived classes, such as ViewResult, JsonResult, etc. The framework executes the appropriate result, which generates the response content.

View Rendering: If the action result is a ViewResult, the view engine is invoked to render the corresponding view. The view combines the data provided by the controller with the HTML markup to produce the final HTML response.

Response: The fully rendered HTML response is sent back to the client. This includes any HTTP headers, cookies, and the response body.

ASP.NET Core MVC Request Life Cycle:

The request life cycle in ASP.NET Core MVC refers to the sequence of events that occur when an HTTP request is made to your application and how the framework handles and processes that request. Understanding the request life cycle is crucial for building and troubleshooting applications effectively. Here’s a high-level overview of the typical request life cycle in ASP.NET Core MVC:

  1. Incoming Request: A client (browser, API client, etc.) sends an HTTP request to the ASP.NET Core application.
  2. HTTP Request Pipeline: The request goes through the ASP.NET Core HTTP request pipeline, which is a series of middleware components that process the request. Middleware can perform tasks like authentication, authorization, logging, and more.
  3. Routing: The routing middleware examines the request URL to determine which controller and action method should handle the request. Routes are configured in the Startup.cs file using the app.UseEndpoints method.
  4. Controller Creation: Once the appropriate route is determined, the MVC framework creates an instance of the corresponding controller.
  5. Action Method Selection: The framework identifies the specific action method within the controller that should handle the request based on the route’s configuration.
  6. Model Binding: Model binding is the process of mapping the data in the request (query parameters, form fields, route values, etc.) to parameters of the action method.
    The framework automatically performs this mapping based on the method’s parameter names and data types.
  7. Action Execution: The selected action method is executed. It can perform business logic, access databases, and prepare data for the view.
  8. View Rendering: The action method returns a view (usually an HTML template) that should be rendered and returned to the client. The view may contain placeholders for dynamic data that will be replaced during rendering.
  9. View Engine: The view engine (Razor, for example) processes the view, which replaces placeholders with actual data and generates HTML output.
  10. Response: The HTML output from the view engine is included in an HTTP response. Additional response-related middleware might handle compression, caching, and other response manipulations.
  11. Outgoing Response Pipeline: The response goes through the ASP.NET Core HTTP response pipeline, which includes any configured response middleware.
  12. Client Receives Response: The processed response is sent back to the client (browser, API consumer, etc.) that made the initial request.

This is a simplified overview of the ASP.NET Core MVC request life cycle. Keep in mind that ASP.NET Core is highly customizable, and you can extend and modify the request life cycle by using middleware, filters, and other advanced features provided by the framework.

This article explained the Life Cycle of ASP.NET 6 MVC request. I hope you enjoy this article, and let me know your thoughts in the comments section.

1 thought on “ASP.NET Core MVC Request Life Cycle”

Leave a Reply

Your email address will not be published. Required fields are marked *