繁体   English   中英

如何在 net core C# 中获取当前环境(QA/Prod/DEV)名称?

[英]How do I get the current environment (QA/Prod/DEV) name in net core C#?

我想在我的代码中获取当前环境的名称(QA/Prod/DEV),这样我就可以在调用 AddJsonFile 时使用该名称

*请注意,此代码不是用于应用程序,而是用于 selenium 单元测试,使用带有 NUNIT 的测试资源管理器测试运行器,因此我没有可以使用的 Startup.cs class 或 ihostingenvironment。

我想这样做,我需要在 launchsettings.json 中检索“Hosting:Environment”或“ASPNETCORE_ENVIRONMENT”值,我认为它应该代表当前的 Visual Studio 进程/会话/环境。 请参阅下面的Environment.GetEnvironmentVariable("Hosting:Environment")了解我如何检索此 launchsettings.json 值。

    public static IConfiguration InitConfiguration()
    {
        LaunchSettingsFixture LaunchSettings = new LaunchSettingsFixture();

        var environmentName = Environment.GetEnvironmentVariable("Hosting:Environment");

        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{environmentName}.json", true)
            .AddEnvironmentVariables();
        var configuration = builder.Build();

        // Testing to see if the above worked
        string url = configuration["url"];
        string driverdirectory = configuration["driverdirectory"];

        return configuration;
    }

在上面的代码中,我期望Environment.GetEnvironmentVariable("Hosting:Environment")返回一个值为“blah”的字符串,因为我在当前进程/配置文件/环境下拉列表中选择了“blah”(下拉运行按钮旁边)。 请参阅下面的照片了解我当前的流程/配置文件选择,并在下面的 launchsettings.json 文件中查看我的 json 文本...

在此处输入图像描述

    {
    "profiles": {
          "Wikipedia.UITest": {
            "commandName": "Project"
               },
          "UAT": {
            "commandName": "Executable",
            "environmentVariables": {
               "Hosting:Environment": "UAT"
               }
           },
          "blah": {
            "commandName": "Executable",
            "environmentVariables": {
              "Hosting:Environment": "Development",
              "containerName": "Testing"
            }
          },
          "Prod": {
            "commandName": "Executable",
            "environmentVariables": {
              "Hosting:Environment": "prod"
            }
          }
        }
      }

取而代之的是Environment.GetEnvironmentVariable("Hosting:Environment")返回我在 launchsettings.json 文件中的最后一个实例(无论我在下拉菜单中选择什么,如屏幕截图所示)。 即它返回一个“prod”的值。 再次,我想提一下这是一个 NUNIT NET CORE 项目,我正在使用测试资源管理器来运行和调试测试(见下面的截图)

在此处输入图像描述

另外,我不知道下面的代码是否相关,但下面是我设置环境变量的方式......

    public class LaunchSettingsFixture
    {
        public LaunchSettingsFixture()
        {
            using (var file = File.OpenText("Properties\\launchSettings.json"))
            {
                var reader = new JsonTextReader(file);
                var jObject = JObject.Load(reader);

                var variables = jObject
                    .GetValue("profiles")
                    //select a proper profile here
                    .SelectMany(profiles => profiles.Children())
                    .SelectMany(profile => profile.Children<JProperty>())
                    .Where(prop => prop.Name == "environmentVariables")
                    .SelectMany(prop => prop.Value.Children<JProperty>())
                    .ToList();

                foreach (var variable in variables)
                {
                    Environment.SetEnvironmentVariable(variable.Name, variable.Value.ToString());
                }
            }
        }

    }  

正如@Mike Zboray正确写的那样,VS 和 Rider 都没有将当前的启动配置文件传递给测试运行程序,因此截至今天无法通过 launchSettings.json 设置环境变量。

关于LaunchSettingsFixture ,它确实会检查所有设置并从每个配置文件中添加每个环境变量,这就是为什么您总是会看到最新的生产配置。 可能在您提到作者的答案中暗示在项目中使用单一启动配置文件。

一种可能的方法是使用构建配置设置并有条件地将 appsettings.*.json 复制到 output 文件夹。 类似于在 .NET Core 之前使用完整的 .NET 框架完成的操作。

在项目文件中,您可以根据构建配置文件配置要复制的文件:

<ItemGroup>
  <None Update="appsettings.$(Configuration).json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
  <None Update="appsettings.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
</ItemGroup>

并且复制了所需的配置文件,您可以将它们添加到配置生成器中:

public static IConfiguration InitConfiguration()
{
    var settingsFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "appsettings.*.json"));
    if (settingsFiles.Length != 1) throw new Exception($"Expect to have exactly one configuration-specfic settings file, but found {string.Join(", ", settingsFiles)}.");
    var settingsFile = settingsFiles.First();

    var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile(settingsFile)
        .AddEnvironmentVariables();
    var configuration = builder.Build();

    // Testing to see if the above worked
    string url = configuration["url"];
    string driverdirectory = configuration["driverdirectory"];

    return configuration;
}

请记住,现在您必须更改构建配置而不是启动配置文件才能针对所选环境运行测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM