ASP.NET Core 6如何在启动期间访问配置

ASP.NET Core 6 how to access Configuration during startup(ASP.NET Core 6如何在启动期间访问配置)

本文介绍了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公开ConfigurationEnvironment属性:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
...
ConfigurationManager configuration = builder.Configuration;
IWebHostEnvironment environment = builder.Environment;

WebApplication返回的WebApplicationBuilder.Build()还公开ConfigurationEnvironment

var app = builder.Build();
IConfiguration configuration = app.Configuration;
IWebHostEnvironment environment = app.Environment;

还要检查migration guide和code samples。

这篇关于ASP.NET Core 6如何在启动期间访问配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:ASP.NET Core 6如何在启动期间访问配置

基础教程推荐