简体   繁体   English

环境变量如何知道我在什么环境上运行以及如何在 C# 中设置它们?

[英]How do environment variables know what environment I am running on and how do I set them in C#?

I am reading a selenium guidebook for c# and they show this:我正在阅读 c# 的 selenium 指南,他们展示了这一点:

class BaseTest
 {
 private static string VendorDirectory = System.IO.Directory.GetParent(
 System.AppContext.BaseDirectory).
 Parent.Parent.Parent.FullName
 + @"/vendor";
 protected IWebDriver Driver;
 public static string BaseUrl;
[SetUp]
 protected void SetUp()
 {
 BaseUrl = System.Environment.GetEnvironmentVariable("BASE_URL") ??
"http://the-internet.herokuapp.com";

But it doesn't show how they are actually setting the environment variables.但这并没有显示他们实际上是如何设置环境变量的。 Is BASE_URL coming from appsettings.json? BASE_URL 是否来自 appsettings.json? I'm not sure where they are getting it from.我不确定他们从哪里得到它。 Right now, I have a class with all of the urls I am using throughout my tests like this:现在,我有一个 class ,其中包含我在整个测试中使用的所有网址,如下所示:

public static class Urls
{
    public static readonly string baseUrl = "https://localhost:5001/";
    public static readonly string aboutUrl = $"{baseUrl}about";
    public static readonly string citiesUrl = $"{baseUrl}cities";
    public static readonly string countriesUrl = $"{baseUrl}countries";
}

I don't think this is the best way to do it and want to try to use environment variables instead but I am not sure how to do that.我认为这不是最好的方法,我想尝试使用环境变量,但我不知道该怎么做。 When I change from localhost to a production environment how I have it now will obviously break.当我从 localhost 更改为生产环境时,我现在拥有的方式显然会中断。 How can I set the baseUrl so it knows what environment I am in?如何设置 baseUrl 以便它知道我所处的环境?

EDITED My test solution is in a separate repo from my project solution.编辑我的测试解决方案与我的项目解决方案位于单独的存储库中。 My test solution is a c# xunit test project.我的测试解决方案是 c# xunit 测试项目。 I added an appsettings.json file to my solution.我在我的解决方案中添加了一个 appsettings.json 文件。 It looks like this看起来像这样

{
  "Base_Url": "https://testurl/",
  "AllowedHosts": "*"
}

Inside one of my tests that uses the url, I am doing this在我使用 url 的一项测试中,我正在这样做

        public static IConfiguration InitConfiguration()
        {
            var config = new ConfigurationBuilder()
               .AddJsonFile("appsettings.json")
               .Build();
            return config;
        }
        [Fact]
        public void LoadFaqs()
        {
            using IWebDriver driver = new ChromeDriver();
            var config = InitConfiguration();

            var faqurl = config["Base_Url"] + "faqs";
            driver.Navigate().GoToUrl(faqurl);
         }

When I run my test, it is failing because it cannot find my appsettings.json file.当我运行我的测试时,它失败了,因为它找不到我的 appsettings.json 文件。 I also tried putting it inside my test folder and it still couldn't find it.我也尝试将它放在我的测试文件夹中,但它仍然找不到它。 I'm not sure what I am doing wrong.我不确定我做错了什么。

Environment variable are set by the Windows system with predefined values the most common ENV variable is PATH you can display env variables on cmd with: echo %ENV_NAME% for example echo %PATH% gives you:环境变量由 Windows 系统使用预定义值设置,最常见的 ENV 变量是 PATH,您可以在 cmd 上显示环境变量: echo %ENV_NAME% 例如echo %PATH%为您提供:

C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;

Env variables is a way to pass parameters between a parent process to a child process ( in the cases where args on command lines are a problem) Then env context is only known by the child process and disappear once the process is killed.环境变量是一种在父进程之间将参数传递给子进程的方法(在命令行上的参数有问题的情况下)然后环境上下文只有子进程知道并且一旦进程被杀死就会消失。 Your selenium launcher might set additional variable with win api like:您的 selenium 启动器可能会使用 win api 设置其他变量,例如:

public static void SetEnvironmentVariable (string variable, string? value);

SetEnvironmentVariable 设置环境变量

In your example I would say: do not care about how selenium set this env variable, just take the content of BASE_URL ( hoping it is not empty....)在您的示例中,我会说:不要关心 selenium 如何设置此环境变量,只需获取 BASE_URL 的内容(希望它不为空....)

Locally, they must be setting them up by using either the project configuration (this is for Visual Studio):在本地,他们必须使用项目配置(这是用于 Visual Studio)来设置它们:

Project properties -> Debug tab -> Environment variables

项目属性 -> 调试选项卡 -> 环境变量

or by running some MSBuild scripts/tasks on build events that ensure the environment variables are added.或者通过在构建事件上运行一些 MSBuild 脚本/任务来确保添加环境变量。 ( quick search on SO ). 快速搜索SO )。 Or by adding them manually on the code when the test host is being built somehow (I'm guessing this is for some functional or integration testing)或者在以某种方式构建测试主机时在代码中手动添加它们(我猜这是用于某些功能或集成测试)

In CI/CD pipelines they are set up depending on the platform you're using (Github, Gitlab, Azure DevOps etc)在 CI/CD 管道中,它们的设置取决于您使用的平台(Github、Gitlab、Azure DevOps 等)

The downside of using hard-coded classes for configuration is that whenever the configuration changes (like when you change your environment and instead of pointing to a local api you need to point to the production one), you need to change/recompile your code, like you said.使用硬编码类进行配置的缺点是,每当配置更改时(例如,当您更改环境而不是指向本地 api 时,您需要指向生产环境),您需要更改/重新编译您的代码,像你说的。

So yeah, I'd say have a look and explore those options.所以,是的,我会说看看并探索这些选项。 Configuration can use several configuration providers . 配置可以使用多个配置提供程序 On asp.net core, by default, they use one called ChainedConfigurationSource , which includes reading from the appsettings.json files, environment variables etc.在 asp.net 内核上,默认情况下,他们使用一个名为ChainedConfigurationSource的内核,其中包括从 appsettings.json 文件、环境变量等读取。

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

相关问题 如何在 C# 中获取和设置环境变量? - How do I get and set Environment variables in C#? 如何在Visual Studio 2010中设置环境变量? - How do I set Environment Variables in Visual Studio 2010? 我该如何替换PATH环境变量以在C#中使用空格将那些变量加双引号和反斜杠? - How do I replace PATH Environment variables to double quote + backslashes those which have spaces in C#? 我如何确保C#的Process.Start将扩展环境变量? - How do I ensure C#'s Process.Start will expand environment variables? C#如何将环境变量作为字符串返回 - C# how do i return an environment variable as a string 如何在 C# 中的 AWS Lambda 项目中设置和获取环境变量 - How do I set & fetch Environment variable in AWS Lambda Project in C# 如何设置环境来解决 Visual Studio 中的 LeetCode 问题? C# - How do I set up an environment to solve LeetCode problems in Visual Studio? C# 如何使用从环境变量配置中设置的变量在SSIS包中设置变量? - How do I set variables in an SSIS package using variables that are set from a Environment Variable Configuration? 如何在C#中永久设置环境变量 - How to set Environment variables permanently in C# 使用 C# 如何使用表单设置变量? - using C# how do i set variables using a Form?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM