3

我在 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 : '值不能为空。'

你有什么主意吗 ?

4

2 回答 2

3

该方法IServiceCollection.GetConnectionString只是在键中添加前缀ConnectionStrings:

然后Configuration.GetConnectionString("Web")类似于Configuration["ConnectionStrings:Web"]

在您的情况下,您需要:

Configuration["ConnectionStrings:Web:ConnectionString"]
//or
Configuration.GetConnectionString("Web:ConnectionString")
于 2020-12-17T08:00:16.817 回答
2

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

公共无效配置服务(IServiceCollection 服务){

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

}

于 2020-12-17T08:21:43.813 回答