Accessing Configuration in ASP.NET Core 6 Applications
In ASP.NET Core 6 and later, the Startup.cs
class is no longer used. Instead, the WebApplicationBuilder
and WebApplication
classes provide access to configuration and environment settings.
Accessing Configuration via WebApplicationBuilder
The WebApplicationBuilder
, obtained via WebApplication.CreateBuilder(args)
, directly exposes the Configuration
and Environment
properties:
<code class="language-csharp">var builder = WebApplication.CreateBuilder(args); // Access configuration IConfiguration configuration = builder.Configuration; // Access environment IWebHostEnvironment environment = builder.Environment; </code>
This approach allows you to access and modify configuration settings during the application's startup phase.
Accessing Configuration via WebApplication
Alternatively, the WebApplication
object (obtained from builder.Build()
) also provides access to the Configuration
and Environment
properties:
<code class="language-csharp">var app = builder.Build(); // Access configuration IConfiguration configuration = app.Configuration; // Access environment IWebHostEnvironment environment = app.Environment;</code>
This is useful for accessing configuration after the application has started.
Example: Retrieving Connection String from appsettings.json
Here's how to read a connection string from the appsettings.json
file:
<code class="language-csharp">using Microsoft.Extensions.Configuration; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); IConfiguration config = builder.Configuration; // Retrieve the connection string string connectionString = config.GetConnectionString("ConnectionString"); // Preferred method for connection strings // Add DbContext using the connection string builder.Services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connectionString));</code>
This example demonstrates the preferred method of retrieving connection strings using GetConnectionString()
. Using this method is generally recommended for better maintainability and security.
By leveraging the Configuration
and Environment
objects, developers can effectively manage configuration data and hosting environment details within their ASP.NET Core 6 applications.
The above is the detailed content of How to Access IConfiguration and IHostEnvironment in ASP.NET Core 6 ?. For more information, please follow other related articles on the PHP Chinese website!