Cant read values from Json file after publishing

830 Views Asked by At

I can read values (value1,Value2) while development, Cant read them after publishing what maybe the problem?

public  IConfigurationRoot Configuration { get; set; }

public Startup(IHostingEnvironment env)
    {
        Configuration = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json")
        .Build();
    }

public void readValues()
    {
        var val1 = ($"{Configuration["Value1"]}");
        var val2 = ($"{Configuration["Value2"]}");
    }

Json:

    {
       "Value1": "Hello",
       "Value2": "World"
    }
2

There are 2 best solutions below

0
On BEST ANSWER

Change your constructor that you added to this:

public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json");

            Configuration = builder.Build();
        }

public IConfiguration Configuration { get; }

This will work just fine.

2
On

Perhaps your publish job isn't copying the appsettings.json to the publish folder?

You can confirm that by checking the contents of the directory you app was published to. Are you publishing with .NET Core CLI? Like: dotnet publish -c Release?

What version are you targeting? In case it's netcoreapp2.0, for example: The publish path goes by bin\Release\netcoreapp2.0\publish. You should be able to find appsettings.json there.

If it's not there you can set fix it by changing the project file (csproj):

  </PropertyGroup>
  <ItemGroup>
    <None Update="appsettings.json">
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </None>
  </ItemGroup>

If that's not the problem and the file is in fact in the publish directory, it might be the directory where you are invoking the program is not the publish directory and in runtime the code doesn't find appsettings.json

If none of those help you, please provide more context like share the project and details on how you are running the published version.