ASP.NET CORE MVC | System.ArgumentNullException : 'Value cannot be null. ' | Configuration.GetConnectionString

Viewed 128

I'm using MVC on Asp.NET Core, & actually, the Startup doesn't find my ConnectionString written the appsettings.json. I've already tried in 3 different ways (2 in comments). Do not pay attention about the "XXX"s.

Let's see : Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    [...]
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseOracle(Configuration.GetConnectionString("Web")));
    //options.UseOracle(Configuration.GetSection("ConnectionStrings")["Web"]));
    //options.UseOracle(Configuration.GetSection("Web")["ConnectionString"]));
    [...]
}

appsettings.json :

[...]
"ConnectionStrings": {
    "Test1": {
        "ConnectionString": "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=XX.XX.X.XXX)(PORT=XXXX))(CONNECT_DATA=(SERVICE_NAME=XXX)));User Id=XXXXX;Password=XXXXX;",
            "ProviderName": "Oracle.ManagedDataAccess.Client"
    },
    "Web": {
        "ConnectionString": "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=XX.XX.X.XXX)(PORT=XXXX))(CONNECT_DATA=(SERVICE_NAME=XXX)));User Id=XXXXX;Password=XXXXX;",
            "ProviderName": "Oracle.ManagedDataAccess.Client"
    },
    "Test2": {
        "ConnectionString": "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=XX.XX.X.XXX)(PORT=XXXX))(CONNECT_DATA=(SERVICE_NAME=XXX)));User Id=XXXXX;Password=XXXXX;",
            "ProviderName": "Oracle.ManagedDataAccess.Client"
    }
}
[...]

& when I build the project to run in the browser, I've always got this error :

System.ArgumentNullException : 'Value cannot be null. '

Do you have any idea ?

2 Answers

The method IServiceCollection.GetConnectionString just add the prefix ConnectionStrings: in the key.

Then Configuration.GetConnectionString("Web") is similar to Configuration["ConnectionStrings:Web"].

In your case, you need :

Configuration["ConnectionStrings:Web:ConnectionString"]
//or
Configuration.GetConnectionString("Web:ConnectionString")

Yes! you need to add Test1/Web/Test2 ..

public void ConfigureServices(IServiceCollection services) {

services.AddDbContext<ApplicationDbContext>(options =>
    options.UseOracle(Configuration.GetConnectionString("Web:ConnectionString")));

}

Related