ASP.NET Core 6 how to access Configuration during startup(ASP.NET Core 6如何在启动期间访问配置)
问题描述
在早期版本中,我们有Startup.cs类,并且在启动文件中获得如下配置对象。
public class Startup
{
private readonly IHostEnvironment environment;
private readonly IConfiguration config;
public Startup(IConfiguration configuration, IHostEnvironment environment)
{
this.config = configuration;
this.environment = environment;
}
public void ConfigureServices(IServiceCollection services)
{ ... }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ ... }
}
现在在.NET 6(使用Visual Studio 2022)中,我们看不到Startup.cs类。看起来它的日子屈指可数了。那么我们如何获取这些对象,如配置(IConfiguration)和托管环境(IHostEnvironment)
我们如何获取这些对象,比如从appsettngs读取配置?当前Program.cs文件如下所示。using Festify.Database;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddDbContext<FestifyContext>();
////////////////////////////////////////////////
// The following is Giving me error as Configuration
// object is not avaible, I dont know how to inject this here.
////////////////////////////////////////////////
builder.Services.AddDbContext<FestifyContext>(opt =>
opt.UseSqlServer(
Configuration.GetConnectionString("Festify")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
我要从appsettings文件中读取配置。
推荐答案
WebApplication.CreateBuilder(args)
返回的WebApplicationBuilder
公开Configuration
和Environment
属性:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
...
ConfigurationManager configuration = builder.Configuration;
IWebHostEnvironment environment = builder.Environment;
WebApplication
返回的WebApplicationBuilder.Build()
还公开Configuration
和Environment
:
var app = builder.Build();
IConfiguration configuration = app.Configuration;
IWebHostEnvironment environment = app.Environment;
还要检查migration guide和code samples。
这篇关于ASP.NET Core 6如何在启动期间访问配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ASP.NET Core 6如何在启动期间访问配置
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01