Startup cs vs program cs in asp net core 2

Introduction

When with ASP.NET Core 2, you may come across two important files: Startup.cs and Program.cs. files play a crucial role in the configuration and initialization of your ASP.NET Core application. In this article, we will explore the differences between Startup.cs and Program.cs and understand respective purposes.

Program.cs

Program.cs is the entry of your ASP.NET Core application. It contains the Main method, which is the starting point of . The Main method is responsible for an instance of the web host and starting the application.


public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup();
}

In the above , the CreateWebHostBuilder method is responsible for creating an instance of the web host. It uses the WebHost class to create a default web host builder and sets the Startup class as the startup type using the UseStartup method. This ensures that the Startup class is used to configure the application.

Startup.cs

Startup.cs is where you configure your ASP.NET Core application. It contains the ConfigureServices and Configure methods, which are used to configure services and the HTTP request pipeline, respectively.


public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Configure services here
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // Configure the HTTP request pipeline here
    }
}

In the ConfigureServices method, you can register services that your application on. This includes services such as database contexts, authentication, and injection. The Configure method is used to define how the HTTP request pipeline handle incoming requests. This includes middleware configuration, routing, and error handling.

Conclusion

Startup.cs and Program.cs are both essential files in an ASP.NET Core application. Program.cs acts as the entry point and is responsible for creating the web host, while Startup.cs is used to configure the application. Understanding the differences between these files is crucial for building and customizing your ASP.NET Core application.

Rate this post

Leave a Reply

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

Table of Contents