ASP.NET Core Main Method

ASP.NET Core Main Method in .NET 6

In this article, I am going to discuss the ASP.NET Core Main Method in .NET 6 Application with Examples. Please read our previous article, where we discussed the ASP.NET Core Project File with Examples. Program class has drastically changed in .NET 6.0. Please visit our ASP.NET Core 3.1 Main Method article in order to Understand the older versions of ASP.NET Code Main Method. 

Main Method in .NET 6

There is a drastic change in the Main method from .NET 6. Here, we will look at the role of the Program.cs class and Main Method in ASP.NET Core (.NET 6) Applications. The Main method of the Program class is the entry point of our ASP.NET Core Application, where we configure the web host. We also configure and register required services and configure middleware pipelines inside the Main method of the Program class as well as start the application to listen to the incoming HTTP Requests.

What is Program Class?

In ASP.NET Core, the Program class is the entry point for our ASP.NET Core Web Application. It contains the application startup code where we need to

  1. Configure the Web Host, i.e., to host the ASP.NET Core Web Application.
  2. Configure and register the services required by the application, such as MVC, Web API, Razor Pages, etc.
  3. Register Middleware Components, i.e., configure the Application Request Processing Pipeline such as Authentication, Authorization, Routing, etc.
  4. Start the Application so that it can listen to HTTP Requests.
Understanding Program.cs Class File in ASP.NET Core

Create a new ASP.NET core application using the ASP.NET Core Empty template. To create a new Empty ASP.NET Core Web Application, open Visual Studio 2022 and click on the Create a new project tab, as shown in the image below.

Understanding Program.cs Class File in ASP.NET Core

Once you click on the Create a new project tab, it will open the Create a new project window. From this window, you need to select the ASP.NET Core Empty project template and click the Next button, as shown in the image below.

What is a Host in ASP.NET Core?

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 project. First, give an appropriate name for your project (FirstCoreWebApplication), 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.

What is Program Class?

Once you click on the Next button, it will open the Additional Information window. Here, you need to select .NET 6.0 as the Framework. 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 below image.

ASP.NET Core Main Method in .NET 6

That’s it. Once you click on the Create Button, the project is going to be created with the Empty template with the following folder and file structure.

ASP.NET Core Main Method in .NET 6

Open the Program.cs class file, and you will see the following lines. As you can see, the Main Method of the Program class contains four lines of code, and these four lines contain all the initialization code required to create a web server, host the application and start listening for HTTP requests.

ASP.NET Core Main Method in .NET 6

The main method is the entry point of the ASP.NET Core Web Application. While creating the Project, if you uncheck the do not use top-level statements checkbox, then you will not find the class name and Main method name. This is a feature introduced in C# 9, where you do not have to specify a main method. This feature allows us to create one top-level file containing only statements. It will not have to declare the main method or namespace. That top-level file will become the entry point of your application.

The program file creates the web application in three stages. CreateBuild, and Run, as shown in the below image.

ASP.NET Core Main Method in .NET 6

Note: The earlier versions of ASP.NET Core created two files. One is Program.cs, and the other is Startup.cs. The Program.cs are responsible for configuring the host, and the startup class is responsible for configuring the Services and Middlewares. With .NET 6, both are merged into a Program.cs class file.

Let us understand the Program file code in detail.

Step 1: Create (Configuring Web Server, Host, and Services)

var builder = WebApplication.CreateBuilder(args);

The first line of the code in the Main method is to create an instance of the WebApplicationBuilder sealed class. The CreateBuilder is a static method of WebApplication class that accepts the Command line arguments as an input parameter. This method initializes a new instance of the WebApplicationBuilder class with preconfigured defaults such as.

  1. Set up Web Server
  2. Host the Application
  3. Logging
  4. Configuration
  5. Dependency Injection Container
  6. Adds Framework Provided Services

So, the CreateBuilder method creates, initializes, and returns a new instance of the WebApplicationBuilder class. And we then use the WebApplicationBuilder instance to configure and register additional services. The WebApplicationBuilder exposes the following.

  1. IWebHostEnvironment: It provides information about an application’s web hosting environment. It will provide information on whether the application is hosted using In-Process or OutOfProcess Hosting Model. Whether it is using IIS Server or Kestrel Web Server, or both.
  2. IServiceCollection: A collection of services that can be used throughout an application. This is useful for adding user-provided or framework-provided services. It provides methods to register different types of services, such as Transient, Scoped, and Singleton services.
  3. ConfigurationManager: A collection of configuration providers that can be used throughout an application. This is useful for adding new configuration sources and providers.
  4. ILoggingBuilder: A collection of logging providers that can be used throughout an application. This is useful for adding new logging providers.

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

Step 2: Build (Configuring the Middleware Components)

var app = builder.Build();

The Build method of the WebApplicationBuilder class creates a new instance of the WebApplication class. We then use the Web Application instance to set up the Middlewares and endpoints for our ASP.NET Core Application. The template has set one middleware component using the MapGet extension method as follows:

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

Step 3: Run (Starts the Application)

app.Run();

The Run method of the WebApplication instance starts the application and listens to HTTP requests.

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 services and middleware components in .NET 6 Applications in detail.

Understanding MapGet Method in ASP.NET Core:

Routing in ASP.NET Core is responsible for matching the 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 for Handling the Requests. The following is the default code of the Main method of the Program class when we created the ASP.NET Core Empty project.

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

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

            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 /, then the request delegate executes, i.e., the statement () => “Hello World!” will execute, and Hello World! is written to the HTTP response. Now, run the application, and you should get the following output, this output is coming from the MapGet Endpoint.

Understanding MapGet Method in ASP.NET Core

To prove it is a GET request, open the browser developer tool by pressing the F12 key and then go to the Network tab and refresh the page. 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 below image.

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 below image.

ASP.NET Core Main Method in .NET 6 with Examples

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

Role of Main Method in ASP.NET Core:

The Main Method of the Program.cs class is the entry point of our ASP.NET Core Application. It configures and builds the Web host. The Web Host is responsible for running our ASP.NET Core Applications. It does so by calling the CreateBuilder method, and most of the code required to configure the Web Host is already written for us within the CreateBuilder method.

  1. First, the Main Create the WebApplicationBuilder instance using which we can configure required services for our ASP.NET Core Application.
  2. Second, the Main method creates an instance of the WebApplication class, using which we can configure required Middleware Components or EndPoints, which will handle the incoming HTTP Requests.
  3. Third, the Main method starts the application by calling the Run method.

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

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

9 thoughts on “ASP.NET Core Main Method”

  1. 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 *