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

前端 未结 14 1847
南旧
南旧 2020-12-16 10:07

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: connection

相关标签:
14条回答
  • 2020-12-16 10:33

    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.

    0 讨论(0)
  • 2020-12-16 10:34

    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")));            
        }
    
    0 讨论(0)
  • 2020-12-16 10:37

    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;"
    
    0 讨论(0)
  • 2020-12-16 10:38

    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")));
    
    0 讨论(0)
  • 2020-12-16 10:39

    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"];
    
    0 讨论(0)
  • 2020-12-16 10:39

    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.

    0 讨论(0)
提交回复
热议问题