从 IConfiguration 中的其他 appsetting 文件读取的问题

Problem to read from other appsetting file in IConfiguration

我在 .net Core 3.1 中有一个 webapi 项目,还有 2 个应用程序设置文件 appsettings.jsonappsettingsTest.json

appsettings.json 文件:

{
"Section": {
"Mofid": "appSettings.json"
}
}

appsettingsTest.json 文件:

{
"Section": {
    "Mofid": "appSettingsTest.json"
}
}

我在 startup.cs class

的构造函数中写了这段代码
public Startup(IConfiguration configuration, IWebHostEnvironment env)
    {

        configuration = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettingsTest.json")
            .Build();

        Configuration = configuration;
    }

在控制器中我注入了 IOptins<T>IConfiguration 并且我有 2 个动作。

第一个操作读取 IOptions 的设置值,另一个操作从 IConfiguration

读取一个值
public class WeatherForecastController : ControllerBase
{
    private readonly IConfiguration _configuration;
    private readonly MofidOption _option;

    public WeatherForecastController(
        IOptions<MofidOption> options,
        IConfiguration configuration
        )
    {
        _option = options.Value;
        _configuration = configuration;
    }

    [HttpGet]
    public string Get1()
    {
        return _option.Mofid; //read from appsettingsTest.json
    }


    [HttpGet]
    public string Get2()
    {
        return _configuration["Section:Mofid"]; //read from appsettings.json
    }
}

我的问题是 IConfigurationappsettings.json 读取而 IOptionsappsettingsTest.json

读取

我想 IConfiguration 阅读 appsettingsTest.json

我该怎么做?

如果修改启动构造函数中的配置,需要注册到依赖注入框架。

services.AddSingleton<IConfiguration>(Configuration);

您最好从 CreateHostBuilder 方法更改配置。

    public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.AddJsonFile("MyConfig.json",
                optional: true,
                reloadOnChange: true);
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });