0

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 !

1 Answer 1

4

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the response. Configuration.GetSection("api") give me null
It's fine. Y're right. it was a problem to access to the file cuz my appsettings.json was into properties folder ... thank you ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.