Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I move appsettings.json out of the app directory?

I want to put my appsettings.json file outside of the web folder so that I can avoid storing it in source control. How can I do this?

like image 617
Ian Warburton Avatar asked Sep 29 '17 15:09

Ian Warburton


2 Answers

It doesn't like relative paths, it seems. But, this works...

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            if (!hostingContext.HostingEnvironment.IsDevelopment())
            {
                var parentDir = Directory.GetParent(hostingContext.HostingEnvironment.ContentRootPath);
                var path = string.Concat(parentDir.FullName, "\\config\\appsettings.json");

                config.AddJsonFile(path, optional: false, reloadOnChange: true);
            }
        })
        .UseStartup<Startup>()
        .Build();

So, it's another settings file on top of the sources added by default.

like image 176
Ian Warburton Avatar answered Sep 18 '22 18:09

Ian Warburton


If you truly don't want it in your source control, the best advice is to keep it where it is and simply add it to the ignores for your source control, so it's never committed, as @PmanAce suggested.

However, I personally think files like appsettings.json should be committed. They essentially serve to document the configuration necessary for the application. Without that as a guide, how is any one supposed to know what should go in the appsettings.json they'll have to create because it won't be included in the pull from your source control?

That said, there is the issue of storing sensitive data to think about. However, there's other ways around this. You can use other means of configuration such as environment variables and/or user secrets to override anything in appsettings.json. Therefore, for things like connection strings, provide a placeholder in your appsettings.json so it's self-documenting that a value for that needs to be provided, but for your own personal use, utilize user secrets and/or environment variables to override that value with something real. That way, you can freely and safely commit appsettings.json, fully documenting what settings are necessary for your application, without worry that personal or secret information is being included with it.

like image 34
Chris Pratt Avatar answered Sep 18 '22 18:09

Chris Pratt