Environment Configuration
Relevant source files
The following files were used as context for generating this wiki page:The environment configuration for the WEBAPI project is managed through a combination of JSON files and application startup logic. This system defines how the application behaves in different environments (e.g., Development), including database connections, launch settings, and registered services. The core components are launchSettings.json for development-time startup, appsettings.json for application-wide settings, and Program.cs for service registration and pipeline configuration.
This configuration is crucial for both running the application and for development tasks like database migrations. It ensures a clear separation of concerns, allowing settings to be managed independently of the application code.
Launch Settings
The Properties/launchSettings.json file configures the application's startup behavior when running from Visual Studio or using the dotnet run command. It defines multiple profiles for launching the application with different settings.
Sources: Properties/launchSettings.json
Launch Profiles
The project is configured with three distinct launch profiles: http, https, and IIS Express. All profiles are set to run in the Development environment and automatically launch a browser to the /swagger URL.
The diagram below illustrates the launch process for a developer.
This diagram shows the different launch options available to a developer based on the launch profiles.
Sources: Properties/launchSettings.json:16-49
The key settings for each profile are summarized below:
| Profile | Command | Application URL | Environment | Launch Browser |
|---|---|---|---|---|
http | Project | http://localhost:5048 | Development | true |
httpss | Project | https://localhost:7032;http://localhost:5048 | Development | true |
IIS Express | IISExpress | http://localhost:19162 (IIS) | Development | true |
Sources: Properties/launchSettings.json:16-49
A typical profile configuration looks like this:
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7032;http://localhost:5048",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
Sources: Properties/launchSettings.json:28-38
Application Settings (appsettings.json)
The appsettings.json file stores application-level configuration data, such as connection strings and logging levels. These settings are not tied to a specific launch profile and are used by the application at runtime.
Sources: appsettings.json
Connection Strings
The primary configuration in this file is the database connection string. The application connects to a SQL Server database defined by the UserDataBase key.
{
"ConnectionStrings": {
"UserDataBase": "Server=MSI;Database=DongHo3;Trusted_Connection=true;TrustServerCertificate=True;"
}
}
Sources: appsettings.json:2-4
Logging
Logging verbosity is also configured here, with the default level set to Information.
| Section | Key | Value | Description |
|---|---|---|---|
Logging.LogLevel | Default | Information | The default logging level for all providers. |
Logging.LogLevel | Microsoft.AspNetCore | Warning | Overrides the logging level for ASP.NET Core components to be less verbose. |
Sources: appsettings.json:6-9
Database Configuration
The database connection is established at startup using the connection string from appsettings.json. This process is handled in Program.cs for runtime and in UserDBContextFactory.cs for design-time operations like creating migrations.
Runtime DbContext Registration
In Program.cs, the UserDBContext is registered as a service. The UseSqlServer method is configured with the UserDataBase connection string.
// Program.cs
builder.Services.AddDbContext<UserDBContext>(option =>
{
option.UseSqlServer(builder.Configuration.GetConnectionString("UserDataBase"));
});
Sources: Program.cs:20-23
Design-Time DbContext Factory
For Entity Framework Core tools to work (e.g., dotnet ef migrations add), the UserDBContextFactory class provides a way to create a UserDBContext instance. It manually builds a configuration object, reads appsettings.json, and retrieves the connection string.
// Data/UserDBContextFactory.cs
public class UserDBContextFactory : IDesignTimeDbContextFactory<UserDBContext>
{
public UserDBContext CreateDbContext(string[] args)
{
IConfigurationRoot configurationRoot = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
var connectionString = configurationRoot.GetConnectionString("UserDataBase");
var optionBuilder = new DbContextOptionsBuilder<UserDBContext>();
optionBuilder.UseSqlServer(connectionString);
return new UserDBContext(optionBuilder.Options);
}
}
Sources: Data/UserDBContextFactory.cs:7-20
The following diagram illustrates how the connection string flows from configuration files to the DbContext.
This diagram shows the two paths for database context initialization: at runtime via Program.cs and at design-time via UserDBContextFactory.cs.
Sources: appsettings.json:2-4, Program.cs:20-23, Data/UserDBContextFactory.cs:7-20
Entity Configuration
The UserDBContext applies all entity type configurations when the model is being created. This is done by calling ApplyConfiguration for each configuration class. This modular approach keeps entity-specific database schema definitions separate.
// Data/UserDBContext.cs
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Apply all configurations
modelBuilder.ApplyConfiguration(new UserConfiguration());
modelBuilder.ApplyConfiguration(new OrderConfiguration());
modelBuilder.ApplyConfiguration(new ProductConfiguration());
// ... and others
}
Sources: Data/UserDBContext.cs:12-19
The database schema is a direct result of these configurations. The diagram below shows the relationships between the main entities.
This ER diagram represents the database schema as defined by the Entity Framework Core model configurations.
Sources: Migrations/UserDBContextModelSnapshot.cs, Configuration/UserConfiguration.cs, Configuration/OrderConfiguration.cs, Configuration/ProductConfiguration.cs, Configuration/CategoryConfiguration.cs, Configuration/OrderItemConfiguration.cs, Configuration/AdminConfiguration.cs
Service and Pipeline Configuration
The Program.cs file is the application's entry point and is responsible for registering services for dependency injection and configuring the HTTP request processing pipeline.
Sources: Program.cs
Service Registration
The application registers several services:
| Service | Registration Method | Lifetime | Description |
|---|---|---|---|
| Controllers | AddControllers() | Scoped | Registers controllers to handle API requests. |
| API Explorer | AddEndpointsApiExplorer() | Singleton | Used by Swagger to discover API endpoints. |
| Swagger | AddSwaggerGen() | Singleton | Generates the OpenAPI specification. |
| DbContext | AddDbContext<UserDBContext>() | Scoped | Registers the EF Core database context. |
| Session | AddSession() | Scoped | Enables session state management. |
| IUserService | AddTransient<IUserService, UserService>() | Transient | Registers the user service. |
| IProductService | AddScoped<IProductService, ProductService>() | Scoped | Registers the product service. |
| IOrderService | AddScoped<IOrderService, OrderService>() | Scoped | Registers the order service. |
Sources: Program.cs:12-38
HTTP Request Pipeline
After the application is built, the request pipeline is configured. The order of middleware is important.
The flow of an incoming HTTP request through the pipeline is shown below.
This diagram shows the sequence of middleware that processes an HTTP request.
Sources: Program.cs:43-58
- Swagger (Development Only):
UseSwagger()andUseSwaggerUI()expose the API documentation endpoint. - CORS:
UseCors()is configured to allow requests from any origin, method, and header. - Authorization:
UseAuthorization()applies authorization policies. - Controller Mapping:
MapControllers()routes the request to the appropriate controller action.
Sources: Program.cs:43-58