简体   繁体   English

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

[英]Cannot get connection string from appsettings.json

I'm building my own API web app using ASP.NET Core 2.0. 我正在使用ASP.NET Core 2.0构建自己的API Web应用程序。 But I cannot get my connection string stored in appsettings.json . 但是我无法将连接字符串存储在appsettings.json

Here is my code in the Startup.cs file, the connection variable holds the connection string, but somehow it is always null: 这是我在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();
}

And here is my appsettings.json 这是我的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"
    }
  }
}

And here is my project folder and file structure: 这是我的项目文件夹和文件结构:

Visual Studio中的解决方案结构,其根目录为appsettings文件

In your appsettings.json , the ConnectionStrings section is within the Logging section. 在您的appsettings.jsonConnectionStrings部分位于 Logging部分中。 So you cannot resolve the connection strings from the root IConfiguration object. 因此,您无法从根IConfiguration对象解析连接字符串。

You should change your configuration so that ConnectionStrings is at the root: 您应该更改配置,以使ConnectionStrings位于根目录:

{
  "Logging": {
    …
  },
  "ConnectionStrings": {
    "CoinToolDbContext": "…"
  }
}

Move the ConnectionStrings element outside the Logging section (The closing bracket was in the wrong place) 将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"
    }      
}

And setup the context this way: 并以这种方式设置上下文:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM