.NET Core Web API: 自动加载不正确的 appsettings.json 文件

.NET Core Web API: Automatically Loading Incorrect appsettings.json File

我们有 .NET Core 2.2 Web API 项目,我们使用以下代码根据 DEBUGRELEASE 构建标志加载适当的 appsettings.json 文件.

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseConfiguration(new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
#if DEBUG
        .AddJsonFile("appsettings.Development.json")
#endif
#if RELEASE
        .AddJsonFile("appsettings.Production.json")
#endif
        .AddJsonFile("appsettings.json")
        .Build()
    )
    .UseStartup<Startup>()
    .Build();

我们创建了一个外部项目,它在 Topshelf Windows 服务项目中调用相同的方法。

奇怪的是appsettings.Production.json文件总是加载,不管我们是调试还是发布项目

执行如下操作并在主机系统中设置环境变量OS 然后:

var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

public static IWebHost BuildWebHost(string[] args) =>
  WebHost
    .UseConfiguration(new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())

    .AddJsonFile($"appsettings.json", true, true)
    .AddJsonFile($"appsettings.{environmentName}.json", true, true)

    .Build()
  )
  .UseStartup<Startup>()
  .Build();

编辑:删除了 CreateDefaultBuilder()

看看https://andrewlock.net/exploring-program-and-startup-in-asp-net-core-2-preview1-2/#setting-up-app-configuration-in-configureappconfiguration

查看 CreateDefaultBuilder()

的文档

Remarks

The following defaults are applied to the returned WebHostBuilder:

  • use Kestrel as the web server and configure it using the application's configuration providers,

  • set the ContentRootPath to the result of GetCurrentDirectory(),

  • load IConfiguration from appsettings.json and appsettings.[EnvironmentName].json,

  • load IConfiguration from User Secrets when EnvironmentName is 'Development' using the entry assembly,

  • load IConfiguration from environment variables,

  • load IConfiguration from supplied command line args,

  • configure the ILoggerFactory to log to the console and debug output,

  • and enable IIS integration.

该列表中的第 3 位总是会查看 ASPNETCORE_ENVIRONMENT 环境变量的值(如果未指定,则默认为“Production”),并尝试加载具有该名称的 appsettings 文件。

与其更改代码或使用预处理器指令,不如更改该环境变量的值(例如,更改为“开发”)。

您的 launchSettings.json 文件是这样工作的:

"profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
  ...

不要与 CreateDefaultBuilder() 作对 - 您发布的代码做了很多步骤,该方法已经为您做了(加载文件、设置基本路径等)。

这是 ASP.Net 核心项目给你的默认 Program.cs,它会很好地工作:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

另外,请注意,您在 主 appsettings.json 文件之前 加载环境特定文件。通常你会想要按其他顺序执行此操作。