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

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

我在 Asp.NET Core 上使用 MVC,实际上,Startup 没有找到我的 ConnectionString 写入 appsettings.json。我已经尝试过 3 种不同的方式(评论中有 2 种)。不要关注“XXX”。

让我们看看: 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"
    }
}
[...]

& 当我在浏览器中将项目构建到 运行 时,我总是遇到这个错误:

System.ArgumentNullException:'Value cannot be null. '

你有什么想法吗?

方法IServiceCollection.GetConnectionString只是在key中加上前缀ConnectionStrings:

那么Configuration.GetConnectionString("Web")类似于Configuration["ConnectionStrings:Web"].

对于您的情况,您需要:

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

是的!您需要添加 Test1/Web/Test2 ..

public void ConfigureServices(IServiceCollection 服务) {

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

}