Search code examples
apiasp.net-corestartup

Getting value from appsettings.json returning NullReferenceException: Object reference not set to an instance of an object. in .net core 3


Not sure what am I missing here but I am not getting the values from my appsettings.json in my .NET Core application. I have read almost all about appsettings.json returning NullReferenceException. I know there are duplicate post, but they have not solved the problem

I have done the settings I know, also read online but still returning null. I have refactored my code several times but still running into the

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

ShopAPI.Startup.ConfigureServices(IServiceCollection services) in Startup.cs+

var key = Encoding.UTF8.GetBytes(Configuration["ApplicationSettings : JWT_Secret"].ToString());

System.RuntimeMethodHandle.InvokeMethod(object target, object[] arguments, Signature sig, bool constructor, bool wrapExceptions)

Startup class:

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)
{
      //.Get<Dictionary<string, string>>()

        services.AddOptions();
        var applicationSettings = Configuration.GetSection("AppSetting");
        services.Configure<ApplicationSettings>(applicationSettings);

        //services.AddSingleton(Configuration.GetSection("AppSettings").Get<ApplicationSettings>());

        services.AddControllers();

        services.AddDbContext<ShopDbContext>(option =>
        option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser,IdentityRole>()
           .AddEntityFrameworkStores<ShopDbContext>()
           .AddDefaultTokenProviders();

        services.Configure<IdentityOptions>(options => {
            options.Password.RequireDigit = false;
            options.Password.RequireUppercase = false;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequiredLength = 6;
        });

        services.AddCors();

        //Jwt Authentication configuration

        //var key = Encoding.UTF8.GetBytes(Configuration["ApplicationSettings: JWT_Secret"].ToString());
        var key = Encoding.UTF8.GetBytes(Configuration["AppSetting : JWT_Secret"].ToString());

        services.AddAuthentication(x => {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = false;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false,
                ClockSkew = TimeSpan.Zero
            };
        });
}

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=api2;Trusted_Connection=True;Connection Timeout=120;MultipleActiveResultSets=true"
  },
  "AppSetting": {
    "JWT_Secret": "1234567890123456",
    "Client_URL": "http://localhost:4500"
  },
  "AllowedHosts": "*"
}

Solution

  • I finally fix the error. I think the configuration is different in .net core 3 I actually followed this tutorial.

    for those that might face the same issue

    var applicationSettings = Configuration.GetSection("AddSettings");
    services.Configure<ApplicationSettings>(applicationSettings);
    
    var appSettingsSecretKey = applicationSettings.Get<ApplicationSettings>();
    

    Then pass the variable appSettingsSecretKey to

    var key = Encoding.ASCII.GetBytes(appSettingsSecretKey.JWT_Secret);