Kapé
Kapé

Reputation: 4781

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?

Upvotes: 21

Views: 18759

Answers (2)

Dmitri
Dmitri

Reputation: 766

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.

Upvotes: 0

anserk
anserk

Reputation: 1320

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 ...

Upvotes: 17

Related Questions