agnivesh
agnivesh

Reputation: 115

Dotnet Core 3.1: How to use AddJsonFile with absolute path to file?

I have a dotnet app in which I need to pull in configuration from both relative paths (the regular appsettings.Json, appsettings.Development.json), and also, from the absolute path /config/appsettings.json. I can't find a way to do this. From the docs, the path arg is Path relative to the base path stored in Properties of builder. How can I set it up to read a config from absolute path /config/filename.json?

Motivation: I'm dockerizing the dotnet app, so I am planning to keep configuration that won't usually change between deployments in the regular publish/appsettings.json and deploy specific config in /config/appsettings.json (which is a volume I'll mount on the container at deploy time).

Upvotes: 6

Views: 16557

Answers (3)

Matteo Umili
Matteo Umili

Reputation: 4017

You can edit your CreateHostBuilder method like this:

public static IHostBuilder CreateHostBuilder(string[] args)
{
    var builder = Host.CreateDefaultBuilder(args);
    builder.ConfigureAppConfiguration(cfgBuilder =>
       {
           var provider = new PhysicalFileProvider("/config"); // Create a dedicated FileProvider based on the /config directory
           cfgBuilder.AddJsonFile(provider, "filename.json", true, true); // Add the filename.json configuration file stored in the /config directory
       });
    builder.ConfigureWebHostDefaults(webBuilder =>
       {
            webBuilder.UseStartup<Startup>();
       });

    return builder;
}

Upvotes: 7

Jhakiz
Jhakiz

Reputation: 1609

agnivesh Try this snippet code example:

        public static class AppConfigurations
        {
            private static IConfigurationRoot BuildConfiguration(this IWebHostEnvironment env)
            {
                var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddJsonFile("config/appsettings.json", optional: true, reloadOnChange: true);
                //
                //  TODO
                //
                return builder.Build();
            }
        }

Now call this class function in Startup class contructor:

public Startup(IWebHostEnvironment env)
    {
        _appConfiguration = env.BuildConfiguration();
    }

Upvotes: 2

Stefano Cucchi
Stefano Cucchi

Reputation: 86

I use a trick.. "relative path", but the parent... you can use "../"

Upvotes: 0

Related Questions