gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:54:24 25 4
gpt4 key购买 nike

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

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

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

最佳答案

在您的 appsettings.json 中,ConnectionStrings 部分 Logging 部分中。因此,您无法从根 IConfiguration 对象解析连接字符串。

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

{
"Logging": {

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

关于c# - 无法从 appsettings.json 获取连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48851560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com