Home
Tags:

WebApplicationBuilder

WebApplicationBuilder - minimal hosting model introduced with .NET 6 The WebApplicationBuilder class provides a streamlined way to configure and build a web application. It combines the functionality of the traditional Startup class and Program class into a single, cohesive setup.

var builder = WebApplication.CreateBuilder(args); // This line initializes a new `WebApplicationBuilder` instance, which sets up the application's configuration, logging, and services.

Key Responsibilities / Step-by-Step Explanation:

  1. Configuration: Sets up configuration sources (e.g., appsettings.json, environment variables)
  2. Logging: Configures logging providers and settings
  3. Dependency Injection (DI): Registers services with the DI container
    • Register Services
      • Services are registered with the DI container using builder.Services.AddScoped, builder.Services.AddTransient and builder.Services.AddSingleton
    • Add HTTP Clients
      • HTTP clients are registered using builder.Services.AddHttpClient
    • Add Controllers and Swagger
      • Controllers and Swagger/OpenAPI are configured using builder.Services.AddControllers and builder.Services.AddSwaggerGen
    • Configure Authentication and Authorization
      • JWT authentication and authorization policies are configured using the builder.Services.AddAuthentication and builder.Services.AddAuthorization
  4. Builds the Application:
    • var app = builder.Build();: This line builds the WebApplication instance, which is used to configure the middleware pipeline and run the application
  5. Middleware Pipeline: Configures the middleware pipeline for handling HTTP requests
    • Middleware components such as Serilog request logging, CORS, authentication, and authorization are added to the pipeline.
    • Authentication, and Authorization: app.UseAuthentication() and app.UseAuthorization() are middleware components that are used to handle authentication and authorization in the request processing pipeline. These middleware components are essential for securing your application by ensuring that only authenticated and authorized users can access certain resources.
    • Routing: Routing middleware is responsible for mapping incoming HTTP requests to the appropriate endpoint (controller action, etc) based on the URL and HTTP method.
      • app.MapControllers(): Maps attribute-routed controllers. This method is used to map controller actions that have route attributes defined on them.
  6. Runs the Application:
    • app.Run(): This line starts the web application and begins listening for incoming HTTP requests.