簡體   English   中英

無法從appsettings.json獲取連接字符串

[英]Cannot get connection string from appsettings.json

我正在使用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"
    }
  }
}

這是我的項目文件夾和文件結構:

Visual Studio中的解決方案結構,其根目錄為appsettings文件

在您的appsettings.jsonConnectionStrings部分位於 Logging部分中。 因此,您無法從根IConfiguration對象解析連接字符串。

您應該更改配置,以使ConnectionStrings位於根目錄:

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

將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")));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM