json.net-core.net-core-configuration

Cant read values from Json file after publishing


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"
    }

Solution

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