Access configuration on startup in ASP.NET Core 6
In previous versions of ASP.NET Core, IConfiguration and IHostEnvironment objects were accessible through the Startup.cs class. However, in .NET 6 and above, the traditional Startup class has been removed.
Access configuration and environments in .NET 6
To access Configuration and Environment objects in ASP.NET Core 6 without a Startup class, use the following methods:
1. Use WebApplicationBuilder
The WebApplicationBuilder returned by WebApplication.CreateBuilder(args) provides access to the Configuration and Environment properties:
<code class="language-csharp">var builder = WebApplication.CreateBuilder(args); IConfiguration configuration = builder.Configuration; IWebHostEnvironment environment = builder.Environment;</code>
2. Use WebApplication
The WebApplication returned by WebApplicationBuilder.Build() also exposes Configuration and Environment properties:
<code class="language-csharp">var app = builder.Build(); IConfiguration configuration = app.Configuration; IWebHostEnvironment environment = app.Environment;</code>
Access configuration in Program.cs file
To access the Configuration object in the Program.cs file, use the Configuration property of WebApplicationBuilder:
<code class="language-csharp">var builder = WebApplication.CreateBuilder(args); // 将服务添加到容器。 builder.Services.AddRazorPages(); builder.Services.AddDbContext<FestifyContext>(opt => opt.UseSqlServer( builder.Configuration.GetConnectionString("Festify"))); var app = builder.Build(); // 配置 HTTP 请求管道。 if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.MapRazorPages(); app.Run();</code>
Please note that FestifyContext
needs to be adjusted based on your actual project. This code shows how to use Program.cs
within builder.Configuration
to get the connection string.
The above is the detailed content of How to Access IConfiguration and IHostEnvironment in ASP.NET Core 6 without Startup.cs?. For more information, please follow other related articles on the PHP Chinese website!