Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference another json file in appsettings.json for ASP.NET Core configuration

In 'the old days' using XML configuration it was possible to include partial configuration from another file like this:

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

Now in ASP.NET Core I would like to share some configuration in appsettings.Development.json as well as for example appsettings.Staging.json. Is something like the <appSettings file=""> did also available using the json configuration?

like image 950
Kapé Avatar asked Sep 05 '17 15:09

Kapé


2 Answers

You can add mutliple configuration file in the Startup class:

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();
    }

See here for more details: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration ...

like image 137
anserk Avatar answered Nov 15 '22 15:11

anserk


If you wish to add a file outside of the project solution folder ie "another file" I made it work by setting .SetBasePath("to whatever path where the settings file is") like so:

any-class-name.cs file:

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();
        }
    }
}

Hope this helps.

like image 1
Dmitri K Avatar answered Nov 15 '22 17:11

Dmitri K