【发布时间】:2021-02-19 13:48:30
【问题描述】:
问题是如何从 ASP NET Core 3.1 应用程序的 appsetting.json 文件中获取 ConnectionString? 这是 appsettings.json 文件
"ConnectionStrings": {
"DefaultConnection": "data source=exmaple;initial catalog=example;persist security info=True;user id=example;password=example"
}
在示例中,所有参数都隐藏在名称示例后面
在 Program.cs 类中,我包含文件
static void ConfigureAppConfiguration(WebHostBuilderContext context, IConfigurationBuilder config, string[] args)
{
config
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName.ToLowerInvariant()}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.AddCommandLine(args);
}
当我尝试在 Startup 类中获取连接字符串值时,我得到 null
public void ConfigureServices(IServiceCollection services)
{
var connetctionString = config.GetConnectionString("DefaultConnection");
...
}
为什么连接 == null ?
【问题讨论】:
-
你在哪里以及如何使用这个
ConfigureAppConfiguration? -
由于其他答案未能解决您的问题,这听起来像是路径问题。检查文件是否正确复制到输出目录中(类似于调试模式下的 Debug/bin/)。如果没有,请打开文件的属性并在 Build Actions 上选择“Copy if newer”或“Copy always”。
标签: c# asp.net-core