【问题标题】:How to store an environment variable in a .NET Core console application?如何在 .NET Core 控制台应用程序中存储环境变量?
【发布时间】:2019-10-09 17:45:00
【问题描述】:

example found here之后,代码需要在命令行中setting an environment variable才能运行。

setx storageconnectionstring "<yourconnectionstring>"

是否可以将此变量存储在 .NET Core 控制台应用程序中的某个位置?如果可能,代码将如何访问它?

【问题讨论】:

  • 你可以只使用一个变量 static、injected、constant... 环境变量的目的是针对以下几种情况之一或两种情况:值是秘密的,你不希望它编译到代码,每个环境的值变化,可能更多

标签: .net-core environment-variables


【解决方案1】:

您可以通过命令提示符 (cmd)、powershell 使用以下语法设置环境:

setx variable_name "value_to_store_as_a_string"

或使用系统属性(右键单击这台电脑,选择属性,然后单击高级系统设置) 窗口并单击 Environment Variables... 按钮(您可以查看所有用户和系统环境并创建、编辑或删除它们)。 这些将在重新启动之间保持不变。

或者回到您的问题,您可以使用配置文件,例如 app.config(这是一个 XML 文件)或 appsettings.json(这是一个 JSON文件)。有几种方法可以访问它。 这是一个示例 appsettings.json 文件:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "ConnectionStrings": {
    "SQL": "Data Source=servername;Initial Catalog=databasename;User Id=myuser;Password=complexpassword;",
    "MongoDb": "mongodb://username:password@10.0.0.2:27017,10.0.0.3:27017,10.0.0.3:27017,10.0.00.4:27017/?replicaSet=myreplicaset"
  },
  "variable_name": "string_value",
  "boolean_variable_name": false,
  "integer_variable_name": 30
}
  1. var appSettings = ConfigurationManager.AppSettings;
    
    string myVariable = appSettings["variable_name"];
    
  2. 2.
public static IConfigurationRoot Configuration;

static void Main(string[] args)
{
    var configBuilder = new ConfigurationBuilder()
        .SetBasePath(System.IO.Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json");

    Configuration = configBuilder.Build();

    string myVariable = hostContext.Configuration.GetValue<string>("variable_name");
}
  1. static void Main(string[] args)
    {
        new HostBuilder()
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.SetBasePath(basePath: Directory.GetCurrentDirectory());
            config.AddJsonFile("appsettings.json", optional: true);
            config.AddEnvironmentVariables();
        })
        .ConfigureServices((hostContext, services) =>
        {
            string myVariable = hostContext.Configuration.GetValue<string>("variable_name");
        })
        .RunConsoleAsync().Wait();
    }
    

您可以阅读另一篇帖子here

您可以在here 的 MS 文档中阅读更多内容。

【讨论】:

  • 如何将 .json 架构转换为 ENV 变量?例如:setx ConnectionStrings.SQL = "value"
  • 这里是an answer关于您的问题。
  • 如果我之前的评论不是您想要的,请澄清或单独提出另一个问题。
猜你喜欢
  • 1970-01-01
  • 2020-09-04
  • 2021-01-29
  • 1970-01-01
  • 2017-01-27
  • 2020-02-29
  • 2023-02-07
  • 2019-12-29
  • 2015-04-26
相关资源
最近更新 更多