2

我希望能够使用 appsettings.json、appsettings.Testing.json 为我的 blazor 应用程序检索适当的连接字符串。在测试服务器上,我将系统变量“ASPNETCORE_ENVIRONMENT”设置为“Testing”,并且我有带有连接字符串的 appsettings.Testing.json。由于某种原因,当通过浏览器访问应用程序时,连接字符串是从 appsettings.json 而不是 appsettings.Testing.json 检索的。

如果我在本地环境中从 launchSettings.json 更改/覆盖环境变量,并从 IIS express 启动应用程序,它会选择正确的连接字符串。我需要在 startup.cs 中做些什么吗?

这是我的 Startup.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

这是我的 appsettings.Testing.json:

{
  "_comment": "Environment settings for testing environment",
  "ConnectionStrings": {
    "DBConnectionString": "Server=TEST-SERVER102;Database=Customers;Trusted_Connection=True;"
  }
}

在此处输入图像描述

更新:如果使用以下代码记录当前环境:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            Debug.WriteLine("[Current Environment]" + env.EnvironmentName);

我看到下面的日志语句:[环境]生产

我在微软文档上读到,如果未设置环境,则默认为生产。我确实通过系统变量将环境设置为“测试”。我错过了什么?

4

2 回答 2

0

事实证明,在我的测试服务器上,应用程序托管在其自己的应用程序池中的 IIS 10 中,我必须通过 appcmd.exe 设置环境变量 ASPNETCORE_ENVIRONMENT。

appcmd.exe 设置配置 -section:system.applicationHost/applicationPools /+"[name='Contoso'].environmentVariables.[name='foo',value='bar']" /commit:apphost

于 2020-03-28T17:06:44.850 回答
0

设置全局环境变量后是否重新启动控制台(除非您在当前终端会话中设置它)?

确保您遵循与您的操作系统相关的 ASP.NET Core 文档中提到的规则:设置环境

于 2020-03-27T22:28:26.873 回答