Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

ASP.

NET Core Main Method


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 host. We also configure and register required services and configure middleware pipelines
inside the Main method of the Program class.

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. it will 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.

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, First, open Visual Studio 2022 and then click on the Create a
new project tab as shown in the below image.

Once you click on the Create a new project box, it will open the “Create a new project” window. This
window includes different .NET 6 application templates. Here we will create a simple Web application
from scratch, so select the ASP.NET Core Empty Project template and then click on the Next button
as shown in the below image.

Trainer: Pranaya Kumar Rout Website: https://dotnettutorials.net/


Once you click on the Next button, it will open the following 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 Next button as shown in the image below.

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.

Once you click on the Create button, it will create a new ASP.NET Core Web Application in Visual Studio
2022 using .NET 6 with the following file and folder structure.

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 of code contain all the initialization
code that is required to create a web server, host the application and start listening for HTTP requests.

Trainer: Pranaya Kumar Rout Website: https://dotnettutorials.net/


The main method is the entry point of 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. Create, Build, and Run as shown in the
below image.

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

Trainer: Pranaya Kumar Rout Website: https://dotnettutorials.net/


So, 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 whether the application is hosted using In-Process or
OutOfProcess Hosting Model. Whether it 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 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 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 Application 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

Trainer: Pranaya Kumar Rout Website: https://dotnettutorials.net/


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 and this output is coming
from the MapGet Endpoint.

To prove that 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 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 below
image.

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.

Trainer: Pranaya Kumar Rout Website: https://dotnettutorials.net/


So, the point that you need to remember is, 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 create 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 set web host with default configurations such as it will host the
application with default server (i.e. either IIS or Kestrel) and with default hosting model (i.e. InProcess
or OutOfProcess). So, next we will learn Different Hosting Models.

Trainer: Pranaya Kumar Rout Website: https://dotnettutorials.net/

You might also like