ASP.NET Tutorial: Understanding `Program.cs` and `Startup.cs`

beginner
7 min

ASP.NET Tutorial: Understanding Program.cs and Startup.cs

Welcome to our comprehensive guide on ASP.NET! In this lesson, we'll delve into the two essential files in every ASP.NET Core project - Program.cs and Startup.cs. By the end of this tutorial, you'll have a solid understanding of these crucial files. Let's get started!

šŸŽÆ Program.cs: Entry Point of Your Application

The Program.cs file serves as the entry point for your ASP.NET Core application. It's where the application bootstraps and sets up the hosting environment.

csharp
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace YourProjectName { 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>(); }); } }

šŸ“ Note: Replace YourProjectName with the name of your project.

Main Method

The Main method initializes the application host and starts the application.

CreateHostBuilder Method

This method sets up the hosting environment for the application. It configures the web host defaults, specifying that our application uses the Startup class to configure services and middleware.

šŸŽÆ Startup.cs: Configuration and Middleware Setup

The Startup.cs file is where you configure the services and middleware that make up your application.

csharp
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace YourProjectName { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }

šŸ“ Note: Replace YourProjectName with the name of your project.

ConfigureServices Method

This method configures the services your application requires, such as controllers.

Configure Method

This method sets up the application's middleware pipeline. It first checks if the application is in development mode, and if so, it enables the developer exception page. Then, it configures routing and maps endpoints for controllers.

Quick Quiz
Question 1 of 1

What is the role of the `Main` method in the `Program.cs` file?

Quick Quiz
Question 1 of 1

What does the `ConfigureServices` method do in the `Startup.cs` file?

That's it for this lesson! In the next lesson, we'll dive deeper into controllers and routing. Until then, happy coding! šŸŽ‰