在appsettings.json中引用另一个用于ASP.NET Core配置的json文件

时间:2017-09-05 15:31:44

标签: c# asp.net-core .net-core configuration-files asp.net-core-2.0

过去的岁月'使用XML配置,可以包含来自其他文件的部分配置,如this

<appSettings file="relative file name">
    <!-- Remaining configuration settings -->
</appSettings>

现在在ASP.NET Core中,我想在appsettings.Development.json以及appsettings.Staging.json中共享一些配置。类似<appSettings file="">的东西是否也可以使用json配置?

2 个答案:

答案 0 :(得分:11)

您可以在Startup类中添加mutliple配置文件:

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile("appsettings-Development.json", optional: false)
            .AddJsonFile("appsettings-Staging.json", optional: false)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

请点击此处了解详情:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration     ...

答案 1 :(得分:0)

如果您希望在项目解决方案文件夹之外添加文件,即“另一个文件”,则可以通过将.SetBasePath(“设置为设置文件所在的任何路径”)使其起作用,例如:

any-class-name.cs文件:

using Microsoft.Extensions.Configuration;
namespace your-name
{
    static class ConfigurationManager
    {
        public static IConfiguration AppSetting { get; }
        static ConfigurationManager()
        {
            AppSetting = new ConfigurationBuilder()
                    .SetBasePath("C:/Users/Name/Documents/AnotherSettings/") //instead of .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json")
                    .Build();
        }
    }
}

希望这会有所帮助。