ASP.NET Core Main Method

ASP.NET Core Main Method

In this article, I will discuss the ASP.NET Core Main Method with Examples. Please read our previous article discussing the ASP.NET Core Project File with Examples. The main method has drastically changed from .NET 6. Here, we will look at the role of the Program.cs class and Main Method in ASP.NET Core (.NET 8) Applications.

ASP.NET Core Program Class

The Program class in ASP.NET Core contains the Main method and is used to configure and launch the application. It includes the following:

  • Host Configuration: This sets up the application’s fundamental components, such as the web server, middleware, and services.
  • Environment Configuration: The developer can configure different environments (like Development, Staging, and Production).
ASP.NET Core Main Method

It is similar to the main method used in console or desktop applications. This method is found in the Program.cs class file and is responsible for bootstrapping the application. The Main method in ASP.NET Core serves as the entry point for the application. It’s where the application starts running. 

  • Creating the Host: The Main method is responsible for configuring and building the web host, which will encapsulate all of the application’s resources, such as dependency injection, logging, and configuration settings.
  • Registering the Services: It also configures and registers the services required by the application, such as MVC, Web API, Razor Pages, etc.
  • Register Middleware Components: The Main is also responsible for configuring the Application Request Processing Pipeline using Middleware Components such as Authentication, Authorization, Routing, etc.
  • Running the Application: After building the host and configuring the Request Processing Pipeline, the Main method calls the Run middleware component, which starts the web server and begins listening to incoming HTTP requests.
Understanding Program.cs Class File in ASP.NET Core

Open the Program.cs class file, and you will see the following lines. The Main Method of the Program class contains four lines of code when we created the project with the ASP.NET Core Empty template. This contains all the initialization code required to create a web server, host the application, and start listening for HTTP requests.

Understanding Program.cs Class File in ASP.NET Core

While creating the Project, if you uncheck the do not use top-level statements checkbox, you will not find the class name and Main method name. This feature was introduced in C# 9, where we do not have to specify the Program class name and Main method name. This feature allows us to create one top-level file containing only statements. That top-level file will become the entry point of your application.

It creates the web application in three stages: Create, Build, and Run, as shown in the image below.

ASP.NET Core Main Method

Note: The earlier versions of ASP.NET Core created two files: Program.cs and Startup.cs. The Program.cs is responsible for configuring the host, and the Startup class is responsible for configuring the Services and Middleware. From .NET 6, both are merged into a Program.cs class file. Let us understand the Program file code in detail.

Step 1: Creating the Web Host and Services

var builder = WebApplication.CreateBuilder(args);

The first line of the code in the Main method creates an instance of the WebApplicationBuilder sealed class. The CreateBuilder is a static method of the WebApplication class that accepts the Command line arguments as an input parameter to configure the web host. This statement initializes a builder for the web application with preconfigured defaults, such as.

  1. Set up Web Server (IIS, Kestrel)
  2. Host the Application (InProcess or OutOfProcess)
  3. Logging (Built-in Service => Debug and Console)
  4. Configuration (How to access the Data from Configuration Files)
  5. Dependency Injection Container (IServiceCollection where you can register the built-in and custom services)
  6. Adds Framework Provided Services

We then call the Build method using the WebApplicationBuilder instance. As we progress in this course, we will see how to configure different types of built-in services, such as MVC, Web API, Razor Page, etc. We will also discuss how to create and configure Custom Services. 

Step 2: Building the Application

var app = builder.Build();

The Build method of the WebApplicationBuilder class creates a new instance of the WebApplication class. This statement converts the configurations set up in the builder into an executable application instance. At this point, the application is ready to set up endpoints and start handling requests, but it isn’t running yet.

Step 3: Mapping Endpoints

We then use the Web Application instance to set up the Middlewares for our ASP.NET Core Application. The template has set one middleware component using the MapGet extension method as follows:

app.MapGet(“/”, () => “Hello World!”);

This line maps HTTP GET requests to the root URL (“/”) to a specific request delegate. Here, the delegate is a simple lambda function that returns the string “Hello World!”. This means that when a user accesses the base URL, they receive “Hello World!” as the response.

Step 4: Running the Application

app.Run();

The WebApplication instance’s Run method starts the application. It listens for incoming HTTP requests on the configured ports and begins processing them according to the defined routes and endpoints.

Note: Using the WebApplicationBuilder instance, we will configure the services, and using the WebApplication instance, we will configure the Middleware components required for our application. As we progress in this course, we will discuss How to configure built-in and custom services and middleware components in the .NET 8 Application in detail.

Understanding MapGet Method in ASP.NET Core:

Routing in ASP.NET Core is responsible for matching incoming HTTP Requests (URLs) and navigating those HTTP requests to the application’s executable endpoints, which will handle the request. Endpoints are nothing but the application’s executable code that will execute to Handle the Requests. The following is the default code for the Main method of the Program class when we created the ASP.NET Core Empty project.

namespace FirstCoreWebApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //Configuring Web Host and Services
            var builder = WebApplication.CreateBuilder(args);

            //Building the Application
            var app = builder.Build();

            //Mapping Endpoints
            app.MapGet("/", () => "Hello World!");

            //Running the Application
            app.Run();
        }
    }
}

The above example code configures a single endpoint using the MapGet method. With the MapGet endpoint, when an HTTP GET request is sent to the application root URL /, the request delegate executes, i.e., the statement () => “Hello World!” will execute, and Hello World! will be written to the HTTP response. Now, run the application, and you should get the following output, which is coming from the MapGet Endpoint.

Understanding MapGet Method in ASP.NET Core

To prove that it is a GET request, open the browser developer tool by pressing the F12 key, go to the Network tab, and refresh the page again. Then click on the local host, and you will see the Request URL as https://localhost:7279/ and the Request Method as GET, as shown in the image below.

Understanding MapGet Method in ASP.NET Core

With the MapGet endpoint, we can only send HTTP GET requests to the server from the application root URL /. Now, let us add something to the URL and press the enter button,, as shown in the image below.

Why We Have the Main Method in ASP.NET Core Web Application

So, you need to remember that if the request method is not GET or the URL is not /, then no route matches, and we will get an HTTP 404 Not Found Error.

Why We Have the Main Method in ASP.NET Core Web Application

Despite ASP.NET Core being focused on web applications, it still uses the Main method because:

  • It aligns with the standard .NET application model, making it easier for developers to transition between different types of .NET applications.
  • Having a Main method gives developers explicit control over how the application starts, configures services, and handles different environments. This is important for more complex applications that require advanced configurations.
  • The Main method is essential for managing the application’s lifecycle. It controls when the application starts and stops, which is important for managing resources effectively.

Next=> The CreateBuilder method sets the web host with default configurations, such as hosting the application with the default server (e.g., either IIS or Kestrel) and the default hosting model (e.g., InProcess or OutOfProcess). So, next, we will learn about Different Hosting Models.

In the next article, I will discuss the ASP.NET Core InProcess Hosting Model with Examples. In this article, I will try to explain the ASP.NET Core Main Method with Examples. I hope this article will help you understand the ASP.NET Core Main Method in .NET Applications.

10 thoughts on “ASP.NET Core Main Method”

  1. blank

    Could you please explain CreateHostBuilder() in a very simple way, it’s very difficult to understand whatever you explained

Leave a Reply

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