What is the purpose of Program.cs file in C# ASP.NET Core project?

CsharpServer Side ProgrammingProgramming

ASP.NET Core web application is actually a console project which starts executing from the entry point public static void Main() in Program class where we can create a host for the web application.

public class Program{
   public static void Main(string[] args){
      BuildWebHost(args).Run();
   }
   public static IWebHost BuildWebHost(string[] args) =>
   WebHost.CreateDefaultBuilder(args)
   .UseStartup<startup>()
   .Build();
}

The WebHost is a static class which can be used for creating an instance of IWebHost and IWebHostBuilder with pre-configured defaults.

The CreateDefaultBuilder() method creates a new instance of WebHostBuilder with pre-configured defaults. Internally,

it configures Kestrel, IISIntegration and other configurations. The following is CreateDefaultBuilder() method.

  • Sets the “Content Root” to be the current directory
  • Allows Command Line args to be pushed into your configuration object
  • Adds both appsettings.json and appsettings.{Environment}.json to be loaded into the configuration object
  • Adds environment variables to the configuration object
  • If in Development, allows the loading of secrets.
  • Adds Console/Debug loggers
  • Tells the app to use Kestrel and to load Kestrel configuration from the loaded config
  • Adds Routing
  • Adds IIS Integration

When we want to host our application into iis we need to add UseIISIntegration() method specifies the IIS as the external web server.

UseStartup<startup>() method specifies the Startup class to be used by the web host. we can also specify our custom class in place of startup.

Build() method returns an instance of IWebHost and Run() starts web application till it stops.

raja
Published on 25-Sep-2020 14:20:23
Advertisements