首先,不要将敏感数据(登录名、密码、API 密钥)保存在 appsettings.json 中,因为您可能会不小心将其提交给 Verison Control,从而导致您的凭据泄露。为此,您必须使用 User Secrets 工具进行开发,有关详细信息,请参阅User Secret documentation。
其次,阅读Configuration.GetConnectionString("DefaultConnection");方法的工具提示文档。它明确指出`GetConnectionString 是一个
GetSection(“ConnectionStrings”)[名称]的简写
话虽如此,您的 appsettings.json 必须如下所示:
{
...,
"ConnectionStrings":
{
"DefaultConnection" : "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;"
}
}
或在使用用户机密时:
dotnet 用户机密集 ConnectionStrings:DefaultConnection Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
更新
在控制台应用程序中使用它是完全一样的。配置包不是 ASP.NET Core 特定的,可以单独使用。
所需的包是(取决于您要使用的包
"Microsoft.Extensions.Configuration": "1.0.0",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0",
并且构建配置的代码与 ASP.NET Core 中的代码完全相同。与其在Startup.cs 中执行,不如在Main 方法中执行:
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
// You can't use environment specific configuration files like this
// becuase IHostingEnvironment is an ASP.NET Core specific interface
//.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddUserSecrets()
.AddEnvironmentVariables();