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如何在启动期间访问配置
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01