C# .Net核心配置拉连接字符串提供程序错误
我正在尝试为我的.Net core 2应用程序设置环境配置。我有2个C# .Net核心配置拉连接字符串提供程序错误,c#,configuration,.net-core,C#,Configuration,.net Core,我正在尝试为我的.Net core 2应用程序设置环境配置。我有2个appSettingsconfig appSettings.json "ConnectionStrings": { "DefaultConnection": "Server=staging.com;Database=staging;User Id=staging;Password=pwd" } appsettings.development.json "ConnectionStrings": { "DefaultCon
appSettings
config
appSettings.json
"ConnectionStrings": {
"DefaultConnection": "Server=staging.com;Database=staging;User Id=staging;Password=pwd"
}
appsettings.development.json
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=staging;User Id=local;Password=pwd"
}
在my Startup.cs中,我的配置设置如下:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
当我去拿连接线的时候
var connectionString = Configuration.GetConnectionString("DefaultConnection");
这是在appsettings.json中返回的,而不是appsettings.development.json,但是当我检查这是否是开发环境env.IsDevelopment()
时,它返回true
如何从配置中获取正确的连接字符串
这将返回stagine,而不是development。然而,当我检查这是否是开发环境env.IsDevelopment()
时,它返回true
您之所以获得开发配置,是因为您仍处于开发环境中,这就是为什么env.IsDevelopment()
返回true
要告诉ASP.Net Core您处于一个暂存
环境中,您需要通过project属性和set-environment属性对其进行配置
转到Debug
选项卡,然后确保环境变量部分将ASPNETCORE\u环境设置为暂存,如下所示:
通过这样做,env.IsDevelopment()
将返回false
,env.IsStaging()
将返回true
。因此,appsettings.development.json将不包括在您的配置中
因为没有appsettings.staging.json,所以您将获得appseting.json设置,然后是您要查找的DefaultConnection
旁注:您应该为登台环境创建一个单独的文件appsettings.staging.json,因为appseting.json应该只包含所有环境的通用配置。每个environmentappsettings。[environment].json应添加新设置或覆盖常用设置
旁注:确保
连接字符串
部分的路径位于根级别暂存配置存储在哪里?进入appstettings.staging.json或appsettings.json?staging在应用程序设置中,localhost正在开发中,我期待localhost,但我正在进入staging我很确定这可以解决问题,我会在早上确认。我想我需要分开我的配置。这是最好的做法,每个环境分开。谢谢,事实证明,这是连接字符串嵌套得比它应该的更深,它找不到它。嗯。。。您的问题中的配置是正确的,因此我们没有看到该问题:)是的,这解决了问题,因为我在将所有内容移动到appsettings.staging.json时发现了它,但我想我也会记录我的错误,以防其他人来到这里,但仍然无法找出原因