无法从appsettings.json获取连接字符串

时间:2018-02-18 12:16:06

标签: c# asp.net-core entity-framework-core

我正在使用ASP.NET Core 2.0构建自己的API Web应用程序。但我无法将我的连接字符串存储在appsettings.json

以下是Startup.cs文件中的代码,connection变量保存连接字符串,但不知何故它始终为null:

public void ConfigureServices(IServiceCollection services) {
   //Add connection to SQL Server Db in appsettings.json
   var connection = Configuration.GetConnectionString("CoinToolDbContext");
   services.AddDbContext<CoinToolDbContext>(options => options.UseSqlServer(connection));
   services.AddMvc();
}

这是我的appsettings.json

{
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "ConnectionStrings": {
      "CoinToolDbContext": "Data Source=localhost;Initial Catalog=CoinToolDb;Integrated Security=True;Pooling=False"
    }
  }
}

这是我的项目文件夹和文件结构:

Solution structure in Visual Studio with the appsettings file at the root

2 个答案:

答案 0 :(得分:4)

appsettings.json ConnectionStrings部分中,<{1}}部分 部分中的<{strong}部分。因此,您无法从根Logging对象解析连接字符串。

您应该更改配置,以便IConfiguration位于根目录:

ConnectionStrings

答案 1 :(得分:2)

将ConnectionStrings元素移动到Logging部分之外(右括号位于错误的位置)

{
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
       }
      },
      "Console": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
    },
    "ConnectionStrings": {
      "CoinToolDbContext": "Data Source=localhost;Initial Catalog=CoinToolDb;Integrated Security=True;Pooling=False"
    }      
}

以这种方式设置上下文:

public void ConfigureServices(IServiceCollection services) 
{
    services.AddDbContext<CoinToolDbContext>(options.UseSqlServer(Configuration.GetConnectionString("CoinToolDbContext")));
}