Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core 2.0 appsettings.json file location when dealing with multiple projects

Tags:

.net-core

I'm working on a .NET Core 2.1.103 WebAPI application that consists of multiple projects. Each project needs to have its own appsettings.json file. Each project is in its own subdirectory within a master "solution" folder. Here's a simplified version of the directory structure with the relevant directories for my question:

c:\code\my_big_solution
c:\code\my_big_solution\project1
c:\code\my_big_solution\project1\bin\Debug
c:\code\my_big_solution\project2
c:\code\my_big_solution\project2\bin\Debug
c:\code\my_big_solution\project3
c:\code\my_big_solution\project3\bin\Debug

I am having difficulty figuring out where each appsettings.json file must go and how to read them in. I assume from reading other posts that I should automatically copy each project's appsettings.json file to its associated bin\Debug directory. If that's the case, I'm not sure how to work with the Startup constructor. My understanding is that this is the .NET Core 2.0 way of reading a value from an appsettings.json file:

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        string myString = Configuration["blah:blah:blah"];

configuration appears to be getting its appsettings.json file from c:\code\my_big_solution, not c:\code\my_big_solution\project1\bin\Debug or whatever project's Debug directory I want to pull from.

I can't figure out how to pull from the desired directory, other than doing a .NET Core 1.x sort of way of doing it, and that's by changing the constructor so it's passing in an IHostingEnvironment and using a ConstructorBuilder:

 public Startup(IHostingEnvironment env)
 {
     var builder = new ConfigurationBuilder()
         .SetBasePath(env.ContentRootPath ) // This line is wrong, but the correct path would be set here
         .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
         .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
         .AddEnvironmentVariables();

     Configuration = builder.Build();
     string myString = Configuration["blah:blah:blah"];

Although the second solution would work, this bugs me because I'm thinking there is a more "correct" way to do this in .NET Core 2.0. Is there?

like image 458
Andr Avatar asked Apr 17 '18 20:04

Andr


1 Answers

I figured out what was going on. In the launch.json file, I didn't have the correct path set for the cwd parameter. That's why Startup() was looking for the appsettings.json file in the wrong place.

like image 97
Andr Avatar answered Sep 27 '22 22:09

Andr