amin89
amin89

Reputation: 437

ASP.NET Core Configuration - appsettings.json : Value is null

I have this in my appsettings.json file

{
  "api": {
      "users": "/api/users",
      "Default": "/api"
   }
}

I want to deserialize "appsettings.json" into the startup class to obtain value1= "/api/users"

As result, sectionData & value1 are null and I don't know why ..

public class Startup
    {
        public string value1, value2;
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

            if (env.IsDevelopment())
            {
                // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
                builder.AddApplicationInsightsSettings(developerMode: true);
            }

            Configuration = builder.Build();
        }

        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            // setup DI in service container
            services.AddOptions();
            services.AddSingleton<IConfiguration>(Configuration);
            IConfigurationSection sectionData = Configuration.GetSection("Api").GetSection("Users");
            Debug.WriteLine("section Data="+sectionData);
            value1 = Configuration.GetSection("api")["users"];
            Debug.WriteLine("testvvalue1=" + value1);
        }
    }

Thank you in advance for your help !

Upvotes: 0

Views: 4273

Answers (1)

Vladmir
Vladmir

Reputation: 1265

I guess that your file is not read. something wrong with the path to check that you can put .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)

and check if it throws.

Other problem can be that "users" is not section but value. I don't know how it is managed internally. Can you check if Configuration.GetSection("api") is also null?

Upvotes: 4

Related Questions