Value cannot be null. Parameter name: connectionString appsettings.json in starter
Asked Answered
A

26

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
}
Apodal answered 29/11, 2016 at 19:53 Comment(0)
A
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");
Anthesis answered 30/11, 2016 at 15:47 Comment(6)
You keep mentioning "App" but in the Json provided there is no "App", perhaps you mean "Data"? I'm confused.Professor
You are correct @mastazi, good catch! People have been letting that slide for a couple of years now. I have edited the post.Anthesis
Thank you @Anthesis for clarifying that!Professor
There is a typo in var connectionString = Configuration["Data::ConnectionStrings:DefaultConnection"];. The double colon :: should be replaced by a single colon :.Coolant
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:<your connection string name> "value".Matta
Make sure your DbContext constructor also has: Configuration = configuration;Benuecongo
V
39

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

Virgate answered 23/1, 2019 at 21:53 Comment(2)
Just spend half an hour trying different kind of connection strings and this was my problem.... Thanks for the answerUnman
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 :)Varney
C
5

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.

Cabral answered 3/1, 2019 at 5:53 Comment(0)
T
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"];
Tenpenny answered 29/11, 2016 at 20:20 Comment(1)
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.Anthesis
R
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;"
Robyn answered 18/11, 2019 at 16:25 Comment(0)
H
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")));
Hubbs answered 4/12, 2018 at 20:21 Comment(0)
N
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; }
Nunn answered 3/12, 2019 at 12:15 Comment(1)
Please edit your answer to include the proposed code as text (formatted as a code block). Code posted as an image isn't useful.Charron
G
2

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

Gentoo answered 29/1, 2021 at 21:33 Comment(0)
F
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.

Fennie answered 6/10, 2019 at 22:25 Comment(2)
Why the double colon? What is the difference?Oliver
I was still facing the same issue until I found this answer. thanksCoverdale
P
1

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

Priesthood answered 24/5, 2020 at 12:9 Comment(0)
S
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.

Sashasashay answered 4/7, 2020 at 18:52 Comment(0)
C
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")));            
    }
Chrotoem answered 14/8, 2020 at 15:54 Comment(0)
T
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"
}
Triclinic answered 26/7, 2021 at 12:13 Comment(0)
A
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")));
Ague answered 28/10, 2021 at 20:58 Comment(0)
A
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")));
Ament answered 14/6, 2019 at 13:20 Comment(0)
N
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();

Novation answered 9/9, 2020 at 12:40 Comment(0)
N
0

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

Nice answered 1/4, 2021 at 1:26 Comment(0)
C
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.

Citrus answered 11/6, 2021 at 18:19 Comment(0)
G
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

Gwynethgwynne answered 3/7, 2021 at 9:21 Comment(0)
N
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" } }

Nichollenicholls answered 25/4, 2022 at 1:23 Comment(1)
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.Alizaalizarin
E
0

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

connStr = Configuration.GetConnectionString("DefaultConnection");

change to:

connStr = Configuration["DefaultConnection:ConnectionString"]
Edmanda answered 7/5, 2022 at 13:58 Comment(0)
N
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"
},
Numerable answered 19/9, 2022 at 6:47 Comment(0)
O
0

Remove this line from YourProjectName.csproj file:

<Nullable>enable</Nullable>
Osorio answered 3/10, 2022 at 17:36 Comment(0)
R
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.

Reclaim answered 17/11, 2022 at 17:18 Comment(0)
L
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");
       });
Lamrouex answered 18/11, 2022 at 12:22 Comment(0)
V
-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");
Villanueva answered 29/11, 2016 at 20:14 Comment(1)
ConnectionString must not be child of Data, as GetConnectionString('DefaultConnection) is an shorthand for Configuration["ConnectionString:DefaultConnection"]Illtimed

© 2022 - 2024 — McMap. All rights reserved.