简体   繁体   English

在 .NET 核心控制台应用程序中使用 appsettings.ENV.json

[英]Using appsettings.ENV.json in .NET Core Console App

I'm building a console app to do some database work for me and want to set up different appsettings files to store the appropriate connection strings per environment.我正在构建一个控制台应用程序来为我做一些数据库工作,并希望设置不同的 appsettings 文件来为每个环境存储适当的连接字符串。 I have something this working in my Main function at the moment:目前,我的 Main function 中有这样的工作:

static void Main(string[] args)
{
            IConfiguration config = new ConfigurationBuilder()
              .AddJsonFile("appsettings.json", true, true)
              .Build();

            var dbconnection = config["db"];
}

But while this is working, it's just one global appsettings file.但是,虽然这有效,但它只是一个全局 appsettings 文件。 I'd like to be able to create different appsettings for each environment (eg appsettings.Dev.json , appsettings.Staging.json , etc.), but I can't figure out how to feed whatever selection I have in the configuration manager when I run the app to the addjsonfile string.我希望能够为每个环境创建不同的 appsettings(例如appsettings.Dev.jsonappsettings.Staging.json等),但我不知道如何提供配置管理器中的任何选择当我将应用程序运行到 addjsonfile 字符串时。

For some additional context, I'd like to feed this into my dbcontext later in the app if that affects anything.对于一些额外的上下文,如果这会影响任何内容,我想稍后在应用程序中将其输入到我的 dbcontext 中。

The other answers here were helpful, but I wanted to expand on exactly what I did for others that come across this.这里的其他答案很有帮助,但我想详细说明我为遇到此问题的其他人所做的事情。

The first thing you'll want to do is to go into your launch settings.json and add something like this:您要做的第一件事是将 go 放入您的启动设置中。json 并添加如下内容:

{
  "profiles": {
    "DataMigration (Local)": {
      "commandName": "Project",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Local"
      }
    },
    "DataMigration (Dev)": {
      "commandName": "Project",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Dev"
      }
    }
  }
}

This will give you access to an environment variable depending on which profile you launch your project with (note the configuration manager has no impact here).这将使您可以访问环境变量,具体取决于您使用哪个配置文件启动项目(请注意配置管理器在这里没有影响)。

Then you can create different appsetting.json files.然后您可以创建不同的 appsetting.json 文件。 For example, I made an appsettings.Local.json and a appsettings.Dev.json file.例如,我制作了一个appsettings.Local.json和一个appsettings.Dev.json文件。

appsettings.Local.json appsettings.Local.json

{
  "db": "connectionstringhere"
}

and

appsettings.Dev.json appsettings.Dev.json

{
  "db": "connectionstringhere"
}

Now, you can then access the environment variable that you run your app with like so:现在,您可以访问运行应用程序的环境变量,如下所示:

static void Main(string[] args)
{
    var myEnv = System.Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
    IConfiguration config = new ConfigurationBuilder()
        .AddJsonFile($"appsettings.{myEnv}.json", false)
        .Build();

    var dbconnection = config["db"];
}

To take it a step further, instead of doing it here, I made by db context flexible like so:为了更进一步,我没有在此处执行此操作,而是通过 db context 灵活设置,如下所示:

public class ShoppingDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var myEnv = System.Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

        if(myEnv != null)
        {
            IConfiguration config = new ConfigurationBuilder()
                 .AddJsonFile($"appsettings.{myEnv}.json", false)
                 .Build();

            var sl = config[$"db"];
           optionsBuilder.UseSqlServer(sl);
        }
        else
        {
            // we are testing and want local for sure
            IConfiguration config = new ConfigurationBuilder()
                 .AddJsonFile($"appsettings.Local.json", false)
                 .Build();

            var sl = config[$"db"];
            optionsBuilder.UseSqlServer(sl);
        }
    }

    public DbSet<MyTable> MyTables { get; set; }
}

You can have as many configuration files as you want just add a line of code to your configuration builder as below:您可以拥有任意数量的配置文件,只需在配置生成器中添加一行代码,如下所示:

IConfiguration config = new ConfigurationBuilder()
          .AddJsonFile("appsettings.json", false)
          .AddJsonFile($"appsettings.{environmentName}.json", true)
          .Build();

You need also to configure your environement name for your application as shwon below:您还需要为您的应用程序配置您的环境名称,如下所示:

在此处输入图像描述

That fact that you're building a console app is inconsequential: you'd handle this the same way an ASP.NET Core app does (which is actually just a console app too).您正在构建控制台应用程序这一事实无关紧要:您可以像 ASP.NET 核心应用程序一样处理这个问题(实际上也只是一个控制台应用程序)。

.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

Here, env is an instance of IHostingEnvironment , which is not applicable to your case here.在这里, envIHostingEnvironment的一个实例,这里不适用于您的情况。 However, the only purpose of it is to get as the value of the environment configuration value.但是,它的唯一目的是获取作为environment配置值的值。 That value can be set many ways, most typically via the ASPNETCORE_ENVIRONMENT environment variable.该值可以通过多种方式设置,最常见的是通过ASPNETCORE_ENVIRONMENT环境变量。 But, it could also be passed as a command-line argument.但是,它也可以作为命令行参数传递。 Since you're building a console app here, you can provide it however you like.由于您在此处构建控制台应用程序,因此您可以随意提供它。 In the end, you'll simply take the environment value and sub that into filename in the AddJsonFile call.最后,您只需将环境值放入AddJsonFile调用中的文件名中。

// get environment value from either `Environment.GetEnvironmentVariable` or by parsing command line arguments

.AddJsonFile($"appsettings.{myEnvironment}.json", optional: true, reloadOnChange: true);

You can also opt to do configuration in two rounds.您也可以选择分两轮进行配置。 In the first round, you add the environment variable and/or command line argument configuration providers, build that configuration source, and then use that to pull out the environment value for the second configuration setup, ie the one you're actually going to be using.在第一轮中,您添加环境变量和/或命令行参数配置提供程序,构建该配置源,然后使用它为第二个配置设置提取环境值,即您实际将要成为的环境值使用。 That's a bit of overkill for environment variables alone, but if you want to provide the option of providing the value via command line arguments, all that manual parsing can be pain.仅对环境变量来说这有点矫枉过正,但是如果您想提供通过命令行 arguments 提供值的选项,那么所有手动解析都会很痛苦。

暂无
暂无

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

相关问题 appsettings.json 中的哨兵配置与 .Net Core 3 控制台应用程序中的 Serilog - Sentry configuration in appsettings.json with Serilog in .Net Core 3 Console App .NET 核心控制台应用程序 - 未在运行时设置适当的基于 appsettings 的环境变量 - .NET Core Console App - not setting appropriate appsettings based env variable at runtime .Net Core 3 控制台应用程序没有启动类或 Appsettings? - .Net Core 3 console app no Startup class or Appsettings? 发布的控制台应用程序上没有.NET Core 2.0应用程序设置 - No .NET Core 2.0 appsettings on a published console app 从 appsettings.json 将多个端点路由添加到 .net 核心控制台应用程序 - Adding multiple endpoint routes to .net core console app from appsettings.json 控制台应用程序看不到 Appsettings.Development.json .net core 3.1 配置问题 - Appsettings.Development.json do not seen by console app .net core 3.1 configuration problem Docker 中 .NET Core 应用程序的 appSettings.json? - appSettings.json for .NET Core app in Docker? 如何使用 .Net 核心控制台应用程序从 appsettings.json 读取部分? - How to read a section from appsettings.json using .Net core console application? 如何在使用 .NET Core 的控制台应用程序中从 appsettings.json 获取值? - How to get values from appsettings.json in a console application using .NET Core? 如何在控制台应用程序 (.net Core) 中将数据写入 appsettings.json? - How to write data to appsettings.json in a console application (.net Core)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM