locked
Reading from appsettings.json gives null reference exception in .NetCore 3.1 - RRS feed

  • Question

  • User-215451226 posted

    hello.

    problem is exactly as is written in the thread title. proj. is in 3.1 .netcore. appsettings.json file contains a segment AppSettings and under it, a key value. trying to read it gives the following error -

    System.NullReferenceException: 'Object reference not set to an instance of an object.'

    _configuration was null.

    appsettings.json -

    {
      "AppSetting": {
        "Secret": "aSecblabla@ret$pPzD%"
      }
    }

    relevant portions of my startup.cs file -

    public class Startup
        {
            private readonly IWebHostEnvironment _env;
            private readonly IConfiguration _configuration;
    
            public IConfiguration Configuration { get; set; }
    
            public Startup(IConfiguration configuration, IWebHostEnvironment env)
            {
                Configuration = configuration;
    
                Configuration = configuration;
                
                var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddEnvironmentVariables();
    
                this.Configuration = builder.Build();
            }
    
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddOptions();
    
                services.AddControllers();
    
                services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
                services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
    
                var appSettingsSection = _configuration.GetSection("AppSetting");  <------------  this line
                services.Configure<AppSetting>(appSettingsSection);
    
                // configure jwt authentication
                blablabla ....
                blabla 
                bla ...
    
    
                services.AddScoped<IUserService, UserService>();
                services.AddScoped<ILoggingService, LoggingService>();
    
                services.AddMvc();
    
            }
    
           public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                app.UseHttpsRedirection();
    
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            }
        }

    AppSetting.cs file -

    public class AppSetting
        {   
            public string Secret { get; set; }
        }


    what's the trouble? necesary code to read from the json file is written in startup.cs constructor. as you already saw above.

    var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddEnvironmentVariables();
    
               

    I thought that was enough. apparently not. what's the grief? Any idea? WHY the nullreference ??

    Saturday, September 12, 2020 3:07 PM

Answers

  • User711641945 posted

    Hi PGChoudhury,

    PGChoudhury

    private readonly IWebHostEnvironment _env;
            private readonly IConfiguration _configuration;
    
            public IConfiguration Configuration { get; set; }
    
            public Startup(IConfiguration configuration, IWebHostEnvironment env)
            {
                Configuration = configuration;
    
                Configuration = configuration;
                
                var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddEnvironmentVariables();
    
                this.Configuration = builder.Build();
            }
    
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddOptions();
    
                services.AddControllers();
    
                services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
                services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
    
                var appSettingsSection = _configuration.GetSection("AppSetting");  <------------  this line

    From your code,you do not register the _configuration,change like below:

    public Startup(IConfiguration configuration, IWebHostEnvironment env)
    {
        _configuration = configuration;
    
        Configuration = configuration;
    
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddEnvironmentVariables();
        this.Configuration = builder.Build();
    }

    And if you want to get the Secret value,you need change your code like below:

    var appSettingsSection = _configuration.GetSection("AppSetting:Secret"); 
    

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, September 14, 2020 8:46 AM

All replies

  • User475983607 posted

    Your not following the openly published constructs.  https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1

            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential 
                    // cookies is needed for a given request.
                    options.CheckConsentNeeded = context => true;
                    // requires using Microsoft.AspNetCore.Http;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });
    
                string value = Configuration["AppSetting:Secret"];
    
                services.AddControllersWithViews();
                services.AddSingleton<IAesCryptoUtil, AesCryptoUtil>();
            }
    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*",
      "password": "VCEzsHhZrb8jD/yyDIvzWw==",
      "AppSetting": {
          "Secret": "aSecblabla@ret$pPzD%"
        }
    }

    Saturday, September 12, 2020 8:57 PM
  • User-215451226 posted

    mgebhard

    Your not following the openly published constructs.  https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1

            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential 
                    // cookies is needed for a given request.
                    options.CheckConsentNeeded = context => true;
                    // requires using Microsoft.AspNetCore.Http;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });
    
                string value = Configuration["AppSetting:Secret"];
    
                services.AddControllersWithViews();
                services.AddSingleton<IAesCryptoUtil, AesCryptoUtil>();
            }
    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*",
      "password": "VCEzsHhZrb8jD/yyDIvzWw==",
      "AppSetting": {
          "Secret": "aSecblabla@ret$pPzD%"
        }
    }

    in ur posted reply what's the AesCryptoUtil is it relevant. The link u posted does not contain any mention of it. Google shows it's related 2 ccavenue. I suppose I can omit it?? reg. this --

    string value = Configuration["AppSetting:Secret"]

    As far as I remember....  I applied that. nevertheless will see once more. also applied GetSection("AppSetting"). GetChildren().               Did not work

    Sunday, September 13, 2020 10:41 AM
  • User475983607 posted

    PGChoudhury

    in ur posted reply what's the AesCryptoUtil is it relevant. The link u posted does not contain any mention of it. Google shows it's related 2 ccavenue. I suppose I can omit it?? reg. this --

    AesCryptoUtil is not relative to your question.  The highlighted bits are relative.

    PGChoudhury

    string value = Configuration["AppSetting:Secret"]

    As far as I remember....  I applied that. nevertheless will see once more. also applied GetSection("AppSetting"). GetChildren().               Did not work

    The syntax is very simple and the code I shared above works just fine.  The community cannot can't help find the mistakes in your code when you do not share the code you're tried.

    Sunday, September 13, 2020 11:38 AM
  • User711641945 posted

    Hi PGChoudhury,

    PGChoudhury

    private readonly IWebHostEnvironment _env;
            private readonly IConfiguration _configuration;
    
            public IConfiguration Configuration { get; set; }
    
            public Startup(IConfiguration configuration, IWebHostEnvironment env)
            {
                Configuration = configuration;
    
                Configuration = configuration;
                
                var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddEnvironmentVariables();
    
                this.Configuration = builder.Build();
            }
    
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddOptions();
    
                services.AddControllers();
    
                services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
                services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
    
                var appSettingsSection = _configuration.GetSection("AppSetting");  <------------  this line

    From your code,you do not register the _configuration,change like below:

    public Startup(IConfiguration configuration, IWebHostEnvironment env)
    {
        _configuration = configuration;
    
        Configuration = configuration;
    
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddEnvironmentVariables();
        this.Configuration = builder.Build();
    }

    And if you want to get the Secret value,you need change your code like below:

    var appSettingsSection = _configuration.GetSection("AppSetting:Secret"); 
    

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, September 14, 2020 8:46 AM