"Value cannot be null." error in ConfigureServices() method of StartUp.cs in .NET Core

Updated on: March 15, 2021

When you set up connection string in ConfigureServices() method of Startup.cs file, it gives error as "System.ArgumentNullException: 'Value cannot be null.'".

 services.AddDbContext<YourDBContext>(options =>        options.UseSqlServer(Configuration.GetConnectionString("YourDBContext")));

Solution to this 'Value cannot be null.' is:

When you setup connection string to use in ConfigureServices() method of Startup.cs class, it will take ConnectionString from appsettings.json file, But if the ConnectionString is not found in appsettings.json file, then it will give this error. So, whenever you are getting this error, then you can check for whether ConnectionString is exist in appsettings.json file. If exists, then check for any spelling mistake there or is it placed at proper place in appsettings.json file. 

You can add ConnectionString as follows in your appsettings.json file:

"ConnectionStrings": { "YourDBContext": "data source=YourDataSource;initial catalog=DataBaseName;persist security info=True;user id=YourUserId;password=YourPassword;"  }

Once you add ConnectionStrings in your appsettings.json file properly, the above error should go away.