51

I am trying to write my connection string in my appsettings.json file and bring it into my startup file but I keep getting a Value cannot be null. Parameter name: connectionString. I have been using various examples but can't seem to see this new setup with ASP.NET 1.0 Core startup class.

Appsetting.json file:

{
"Data": {
"DefaultConnection": {
  "ConnectionString": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"

},
"Logging": {
  "IncludeScopes": false,
  "LogLevel": {
    "Default": "Debug",
    "System": "Information",
    "Microsoft": "Information"
  }
}
}
}

Method attempting Startup.cs

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();
        Configuration = builder.Build();
    }

 public void ConfigureServices(IServiceCollection services)
    {
        var connStr = Configuration.GetConnectionString("DefaultConnection");
        System.Console.WriteLine(connStr);
        services.AddDbContext<DbContext>(options => options.UseSqlServer(connStr)); //error right here -- Null value
}
enavuio
  • 1,428
  • 2
  • 19
  • 31

26 Answers26

51

First of all, the

 "Data": {
"ConnectionStrings": {
  "DefaultConnection": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"},
}

Is slightly different from the structure you get when you add a "Asp.NET Configuration File" in Visual Studio. When you do that you get

"ConnectionStrings": {
  "DefaultConnection": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"},

without the "Data" JavaScript Object. So that's why the extension method isn't working. It expects this structure. You can use this structure (the one with "Data") anyway and get your connection string like so:

var connectionString = Configuration["Data:ConnectionStrings:DefaultConnection"];

Notice that you are navigating through the JavaScript object tree using : instead of .. That's due to some cross-platform issues with using the ..

If you edit out the "Data":{} you can do this :

var connectionString = Configuration["ConnectionStrings:DefaultConnection"];

Now the extension method will work. Underneath the Microsoft extensions it is the same thing as the code above.

var config2 = Configuration.GetConnectionString("DefaultConnection");
LuvForAirplanes
  • 761
  • 8
  • 23
GlennSills
  • 3,977
  • 26
  • 28
  • You keep mentioning "App" but in the Json provided there is no "App", perhaps you mean "Data"? I'm confused. – mastazi Jul 12 '19 at 09:41
  • You are correct @mastazi, good catch! People have been letting that slide for a couple of years now. I have edited the post. – GlennSills Jul 15 '19 at 12:53
  • Thank you @GlennSills for clarifying that! – mastazi Jul 16 '19 at 02:22
  • There is a typo in `var connectionString = Configuration["Data::ConnectionStrings:DefaultConnection"];`. The double colon `::` should be replaced by a single colon `:`. – Marc Sigrist Oct 17 '19 at 15:10
  • 1
    Thank you! You just saved my life. I spent 2 hours wondering why my connection string for user secrets was not being picked up. Turns out you need to use this exact syntax for it to work: `dotnet user-secrets set ConnectionStrings: "value"`. – Tanveer Badar Mar 30 '20 at 11:50
  • Make sure your *DbContext* constructor also has: `Configuration = configuration;` – Cardi DeMonaco Jr Jan 18 '21 at 02:31
38

I was missing the letter 's' after the ConnectionString property name in the appsettings.json when using Configuration.GetConnectionString("name")

enter image description here

If you want to copy

"ConnectionStrings ": {
  "SpyStore": "Server=(localdb)\\mssqllocaldb;Database=SpyStore;Trusted_Connection=True;MultipleActiveResultSets=true;"
}

The method wording GetConnectionString confused me, I hovered over it and oh be hold it was looking for ConnectionStrings property name instead of ConnectionString

StefanJM
  • 1,533
  • 13
  • 18
  • 1
    Just spend half an hour trying different kind of connection strings and this was my problem.... Thanks for the answer – Jeroen Apr 11 '20 at 15:41
  • 1
    lol, can't believe that I spent long time trying to figure out what wrong I did, and finally it's one letter missing, thank you Stefan for posting that :) – amal50 Sep 02 '20 at 09:29
4

DefaultConnection is the inner object in the json structure and it is the child of Data object.

So if you want to be exact with your config file you can use

var connStr = Configuration.GetSection("Data")
                           .GetSection("DefaultConnection")["ConnectionString"];
Rudis
  • 1,177
  • 15
  • 30
  • 3
    The GetSection stuff is not required. You can navigate the object tree using a ":' as a delimiter. So Configuration["Data:DefaultConnection:ConnectionString"] is equivalent. See my answer below. – GlennSills Nov 30 '16 at 18:30
4

I had got similar error.My "appsettings.json" file was not loading because the properties of the file was Copy to Output Directory -> Do not Copy. I set that to Copy always save and rebuild.It worked.

3

I got this because I had a connection string with a \ in it, which needed escaping to be a \\. So my localdb connection string was causing a load error like this:

"DefaultConnection": "Server=(localdb)\myinstance;Integrated Security=true;Initial Catlog=my-localdb;"

and was fixed by making it:

"DefaultConnection": "Server=(localdb)\\myinstance;Integrated Security=true;Initial Catlog=my-localdb;"
noelicus
  • 14,468
  • 3
  • 92
  • 111
2

this is was the message that appeared me

Value cannot be null. Parameter name: connectionString

I fix it changed in the startup these lines

services.AddDbContext<AppIdentityDbContext>(options =>
options.UseSqlServer(
Configuration["Data:BookStoreContext:ConnectionString"]));

To

services.AddDbContext<AppIdentityDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("BookStoreContext")));
2

in asp.net core you must add IConfiguration to startUp contractor method and assignee this Parameter to a property inherited from IConfiguration inside class

 public class Startup
{
    public Startup(IConfiguration configuration)
    {
        this.Configuration = configuration;
    }
    public IConfiguration Configuration { get; }
  • 2
    Please edit your answer to include the proposed code as text (formatted as a code block). Code posted as an image isn't useful. – Adrian Mole Dec 03 '19 at 12:44
2

my issue is fixed by fixing a typo enter image description here

Rm558
  • 4,621
  • 3
  • 38
  • 43
1

I experienced this problem using asp.net core 3.0. The workaround fix for me is:

Instead of:

var connectionString = Configuration["ConnectionStrings:DefaultConnection"];

Use this:

var connectionString = Configuration["ConnectionStrings::DefaultConnection"];

The emphasis here is the double colon in the connection configuration.

CYCLONE
  • 541
  • 4
  • 5
1

Another mistake in my case was that I was using ConnectionString, instead ConnectionStrings (Note last 's')

Satya Arya
  • 95
  • 6
1

Maybe you can try this:

services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer("DefaultConnection")
);

Then set your appsettings.json do something like this:

"ConnectionStrings:": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=HOME1_DATABASE;Trusted_Connection=True;MultipleActiveResultSets=true"
},

After that, when a I add migration via the console, it succeeds.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
makampos
  • 11
  • 1
1

While using Postgres SQL the appsettings.Development.json must contain

"ConnectionStrings": {  
      "DefaultConnection": "User ID=user;Password=xxxx;Host=127.0.0.1;Port=5432;Database=abc;Pooling=true"
    }  

Content in the Startup.cs file would be like

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>
        (p => p.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));            
    }
ScareCrow
  • 497
  • 3
  • 6
1

The correct way to add connection strings into your appsetting.json file is the following:

"ConnectionStrings":{
   "DefaultConnection":"Server=localdb)\\MSSQLLocalDB;Datbase=MyShop;Trusted_Connection=true"
}
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
1
  • I get it,it was because the name of connection string that in app settings was difference from that in the configuration that in Startup !!!

  • The right code of connection String Configuration in startup

// replace NAMEHERE with the name of the class that inherits from DbContext
services.AddDbContextPool <NAMEHERE> (opts => opts.UseSqlServer(Configuration.GetConnectionString("here put the same Connection string name that in appsettings")));
Abdelsalam Shahlol
  • 1,621
  • 1
  • 20
  • 31
0

I fought with the null connection string issue far too long, only to find I was doing this:

builder.Services.AddDbContext<MlDataContext>(provider => new MlDataContext(config.GetConnectionString("ConnectionStrings:SqlConnectionString")));

I was using both the ConnectionStrings: prefix AND GetConnectionString. When I removed the prefix it worked:

builder.Services.AddDbContext<MlDataContext>(options => options.UseSqlServer(config.GetConnectionString("SqlConnectionString")));
Slothario
  • 2,830
  • 3
  • 31
  • 47
0

For Postgre Db, Below worked for me

    private readonly IConfiguration _config;

    string connectionString;
    public DataBaseContext(IConfiguration config)
    {
        _config = config;
        connectionString= _config.GetValue<string>("ConnectionStrings:sampleConnection");
    }

Config file:

"ConnectionStrings": { "sampleConnection":".." }

Start up file: services.AddScoped();

Falaq
  • 23
  • 4
0

In my case I had two IConfiguration definitions in my Startup class. Not helpful :)

mateoc15
  • 509
  • 5
  • 18
0

I had this error on the day when usin Asp.Net Core 5. I tried all above solutions with no satisfaction. Then I deleted the "ConnectionStrings" section the appsettings.json file and launched a migration. After the error, I rewrote the section and launched again the migration. All worked fine.

DOUMBIA Mamadou
  • 276
  • 2
  • 10
0

Please make sure you have all you connection strings defined in the app.json. My problem was I had two different projects that added a dbContext in their services config

  1. The identity project which made a reference to the identityDb
  2. The persistence project that all my data access logic

I solved the issue by having both connection strings defined in the app.json

0

try it, it will work for you on version 3.0.0.

public class Startup { private readonly IConfiguration configuration; public Startup(IConfiguration configuration) { this.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.AddControllersWithViews();
        services.AddDbContext<DataContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("MyPortfolio"));
        });
    }

appsettings.json

{

"Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "ConnectionStrings": { "MyPortfolio": "Data Source=(localdbd)\MSSQLLocalDB; initail catalog=MyPortfolioDB; Integrated Security=true" } }

GreenHat
  • 1
  • 3
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 25 '22 at 04:07
0

I had the same problem and this fixed it for me:

connStr = Configuration.GetConnectionString("DefaultConnection");

change to:

connStr = Configuration["DefaultConnection:ConnectionString"]
oguz ismail
  • 1
  • 16
  • 47
  • 69
0

I am having the same error but realize to be an typo.

"ConnectionStringd": {
    "DefaultConnection":  "Server=localhost;Database=BookListRazor;Trusted_Connection=True;MutipleActiveResultSets=True"
},

the correct typing should be

"ConnectionStrings": {
    "DefaultConnection":  "Server=localhost;Database=BookListRazor;Trusted_Connection=True;MutipleActiveResultSets=True"
},
cmhack
  • 3
  • 3
0

Remove this line from YourProjectName.csproj file:

<Nullable>enable</Nullable>
M Komaei
  • 7,006
  • 2
  • 28
  • 34
0

In my case this is a new deployment to a new server. It turns out the environment variable ASPNETCORE_ENVIRONMENT was not set, so .NET Core couldn't get the connection string from appsettings.PROD file, and thus passed null to options.UseSqlServer(connection).

Once I created a new environment variable ASPNETCORE_ENVIRONMENT and set its value to PROD, problem is solved.

Mike
  • 91
  • 1
  • 2
0

instead of using the method given below

builder.Services.AddDbContext<FullstackAPIcontext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("FullStackConnectionString")));

You can directly add the connection string after Usesqlserver .The code snippet is given below

builder.Services.AddDbContext<FullstackAPIcontext>(options =>
       {
           options.UseSqlServer("Server=myserver;Database=FullstackDb;Trusted_Connection=SSPI;Encrypt=false;TrustServerCertificate=true");
       });
-1

You need to change your appsetting.jsonto:

    {
  "Data": {
    "ConnectionStrings": {
      "DefaultConnection": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"

    },
    "Logging": {
      "IncludeScopes": false,
      "LogLevel": {
        "Default": "Debug",
        "System": "Information",
        "Microsoft": "Information"
      }
    }
  }
}

And now will be working:

  var connStr = Configuration.GetConnectionString("DefaultConnection");
M. Wiśnicki
  • 6,094
  • 3
  • 23
  • 28
  • 3
    ConnectionString must not be child of Data, as `GetConnectionString('DefaultConnection`) is an shorthand for `Configuration["ConnectionString:DefaultConnection"]` – Tseng Nov 29 '16 at 20:47