none
ConfigurationSection Issue in ASP.NET Core v2.1

    Pertanyaan

  • Hello, 

    I have a problem with configurations in ASP.NET Core v2.1. Basically when I use IConfigurationRoot.GetSection on a json configuration then an empty configuration file is returned. 

    Here is the startup constructor.

         public Startup(IHostingEnvironment env)
            {
                CurrentEnvironment = env;
    
                var builder = new ConfigurationBuilder()
                        .SetBasePath(env.ContentRootPath)
                        .AddJsonFile("config.json", optional: false, reloadOnChange: true);
                 Configuration = builder.Build();
             }

    Here is my ConfigureServices Method.

        // This method gets called by the runtime. Use this method to add services to the container.
           public void ConfigureServices(IServiceCollection services)
           {
            services.AddOptions();
    
            services.Configure<SmtpConfig>(Configuration.GetSection("EmailConfiguration"));
           }

    Here is my Build WebHost Method

           WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((context, config) =>
                {
                    config.SetBasePath(Directory.GetCurrentDirectory());
                    config.AddJsonFile("config.json", optional: false, reloadOnChange: true);
                  })

    And the config.json

            {
                "EmailConfiguration": {
                    "server": "value"
                },
                "ASecondSection": {
                    "SomeKeyWith": "SomeValue"
            }

    Configuration.GetSection("EmailConfiguration") returns an ConfigurationSection with Value null and .GetValue cannot be used on it.

    Configuration["EmailConfiguration:server"] returns value.

    • Dipindahkan oleh CoolDadTx Rabu, 14 November 2018 16.20 ASP.NET related
    Rabu, 14 November 2018 16.08

Semua Balasan