Asp.Net Core Entry Point

Asp.net Core is a console application that creates a web server. As we know, for console app entry point is Main() method. In the same way for Asp.Net Core also, the Main method is the entry point

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

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

As shown above, the Main() method creates the web host by using CreateHostBuilder, where can we configure web content root location, standard settings for an application like database connection string, and logging settings.

Here we are calling the Startup class, which has ConfigureService() and Configure() methods.

namespace AspNetCoreExp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}

The ConfigureServices() method used to configure services, authorization policies, CORS (Cross-Origin Requests) policies, classes that need to be available in dependency injection, and React application. Services are added by calling IServiceCollection services parameter methods which start with Add.

The Configure() method is used to configure the request/response pipeline. Here we define which middleware should execute and in which order. As shown in the above code, Middleware code invoked by methods that start with Use in the app parameter. We specify authentication middleware also in the Configure() method.