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:
- Configuration: Sets up configuration sources (e.g., appsettings.json, environment variables)
- Logging: Configures logging providers and settings
- Dependency Injection (DI): Registers
services with the DI container
- Register Services
- Services are registered with the DI container using
builder.Services.AddScoped,builder.Services.AddTransientandbuilder.Services.AddSingleton
- Services are registered with the DI container using
- Add HTTP Clients
- HTTP clients are registered using
builder.Services.AddHttpClient
- HTTP clients are registered using
- Add Controllers and Swagger
- Controllers and Swagger/OpenAPI are configured using
builder.Services.AddControllersandbuilder.Services.AddSwaggerGen
- Controllers and Swagger/OpenAPI are configured using
- Configure Authentication and Authorization
- JWT authentication and authorization policies are
configured using the
builder.Services.AddAuthenticationandbuilder.Services.AddAuthorization
- JWT authentication and authorization policies are
configured using the
- Register Services
- Builds the Application:
var app = builder.Build();: This line builds theWebApplicationinstance, which is used to configure the middleware pipeline and run the application
- 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.
- Middleware components such as Serilog request logging,
- Runs the Application:
app.Run(): This line starts the web application and begins listening for incoming HTTP requests.