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.

Understanding Program.cs Class File in ASP.NET Core

When you open the Program.cs class file in an ASP.NET Core project, you will see a few lines of code. These few lines handle all the setup needed to create a web server, configure services, and start the application to listen for HTTP requests.

Understanding Program.cs Class File in ASP.NET Core

If you uncheck the “Do not use top-level statements” checkbox during project creation, you won’t see the class or Main method name. This feature, introduced in C# 9, allows you to write one “top-level” statement, meaning you don’t have to explicitly define the Program class or the Main method. The file itself acts as the application’s entry point.

Note: In earlier versions (before .NET 6), ASP.NET Core used two separate files: Program.cs and Startup.cs. The Program.cs file configured the host, and Startup.cs handled the services and middleware. Starting with .NET 6, these are merged into a single Program.cs file for simplicity.

Program Class:

This is the main class of every .NET application that serves as the entry point.

Main Method:

The Main method is the first method executed when an application runs. It’s a static method, which means it runs without needing to create an object of the Program class. When starting the application, it takes a string array (string[] args) as a parameter to accept any command-line arguments.

ASP.NET Core Main Method

The main method is responsible for doing four things. They are as follows:

  • Creating the Web Host and Configuring the Services
  • Building the Application
  • Setting Up Endpoints, Routing, and Middleware Components
  • Running the Application

Let us understand the Main method in detail:

Step 1: Creating the Web Host and Configuring the Services

var builder = WebApplication.CreateBuilder(args);:

This is the first line of code in the Main method used to create an instance of the WebApplicationBuilder sealed class. The args parameter allows the application to process any command-line arguments passed at application startup. The WebApplicationBuilder instance is responsible for configuring essential services (like Logging, Configuration, MVC, Web API, Dependency Injection, etc.) preconfigured defaults such as:

  • Set up Web Server (IIS, or Kestrel)
  • Host the Application (InProcess or OutOfProcess)
  • Logging (debugging and console logging)
  • Configuration (How to access the Data from Configuration Files)
  • Dependency Injection Container (registering built-in and custom services)

Note: 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 create and configure Custom Services using the WebApplicationBuilder instance.

Step 2: Building the Application

var app = builder.Build();:

After configuring the essential services, when the Build() method is called on the WebApplicationBuilder instance, the actual WebApplication instance is built. The result, the app, represents the application itself. From this point, the application is ready to set up routes, configure the middleware component, and start handling requests, but it isn’t running yet.

Step 3: Setting Up Endpoints, Routing, and Middleware Components

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

This line defines a simple endpoint (or route) that handles HTTP GET requests. So, you need to remember that using the Web Application instance, app, we can set up the Middleware Component, endpoints, routing, etc. for our ASP.NET Core Application

  • app.MapGet(“/”, …);: This maps the root URL (“/”) of the application to a handler function.
  • () => “Hello World!”: This is an inline lambda function (handler function) that returns the string “Hello World!”. When a user sends a GET request to the root URL (e.g., http://localhost/), this route handler returns the string “Hello World!” as the response.

This is a basic HTTP route using the MapGet method, which allows us to handle requests with a lambda function (() => “Hello World!”).

Step 4: Running the Application

app.Run();:

This line starts the web server and begins listening for incoming requests. Without app.Run(), the web server will not start. The Run() method keeps the application running until manually stopped, and it is responsible for handling incoming 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.

Understanding MapGet Method in ASP.NET Core:

Routing in ASP.NET Core is responsible for matching incoming HTTP requests to defined endpoints in our application. Endpoints are executable code that runs in response to a request. 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
    {
        //Entry point to the application
        public static void Main(string[] args)
        {
            // Step 1: Creating the Web Host and Services
            var builder = WebApplication.CreateBuilder(args);

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

            //Step 3: Setting Up Endpoints, Routing and Middleware Components
            app.MapGet("/", () => "Hello World!");

            //Step 4: 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 it is a GET request, open the browser developer tool by pressing the F12 key, 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 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.

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 ASP.NET Core Applications.

10 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 *