在IConfiguration中从其他应用程序设置文件读取的问题。

问题描述 投票:0回答:1

我在.net Core 3.1中有一个webapi项目,我有两个appsettings文件。appsettings.jsonappsettingsTest.json

appsettings.json文件。

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

appsettingsTest.json文件。

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

我把这段代码写在了 startup.cs 阶层

public Startup(IConfiguration configuration, IWebHostEnvironment env)
    {

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

        Configuration = configuration;
    }

在控制器中,我注入了 IOptins<T>IConfiguration 我有两个动作。

第一个动作是读取一个设置值,用 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
    }
}

我的问题是 IConfiguration 读自 appsettings.jsonIOptions 读自 appsettingsTest.json

我想 IConfiguration 读自 appsettingsTest.json

我怎样才能做到这一点?

c# json asp.net-core appsettings .net-core-3.1
1个回答
1
投票

如果你在Startup构造函数中修改了配置,你将需要在DI框架中注册它。

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>();
        });
© www.soinside.com 2019 - 2024. All rights reserved.