【问题标题】:.net core application can't find the correct appsettings using environment variables.net 核心应用程序无法使用环境变量找到正确的 appsettings
【发布时间】:2022-10-15 06:22:28
【问题描述】:

我有一个简单的 .net 核心应用程序。它使用WebApplicationBuilder 在运行时创建应用程序的实例。

program.cs 中的代码如下所示:

    var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

var logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .Enrich.FromLogContext()
    .CreateLogger();

builder.WebHost.ConfigureLogging(logging =>
{
    logging.ClearProviders();
    logging.AddConsole();
    logging.AddSerilog(logger);
});

我的launchsetting.json 看起来像这样:

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:29881",
      "sslPort": 44344
    }
  },
  "profiles": {
    "MyApp.Api": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:7134;http://localhost:5134",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

在本地使用MyApp.Api 配置文件运行此应用程序时,它可以工作。它使用appsetting.Development.json 并将其json 值转换为appsetting.json。

但是,当我将应用程序发布并部署到本地环境之外的服务器时,它不使用提供的appsetting.CURRENT.json。

环境变量设置如下:

Environment=ASPNETCORE_ENVIRONMENT=CURRENT
Environment=DOTNET_ENVIRONMENT=CURRENT

我可以看到文件被部署到正确的目录。

-rw-r--r--  1 root root    2397 Oct 13  2022 appsettings.CURRENT.json
-rw-r--r--  1 root root    1527 Oct 13  2022 appsettings.json

我完全没有想法。任何帮助都深表感谢。

【问题讨论】:

    标签: .net asp.net-core .net-core appsettings


    【解决方案1】:

    我建议一种不同的方法:

    if(builder.Environment.IsProduction())
    {
      builder.Configuration.AddJsonFile(
        "appsettings.CURRENT.json",
        optional: false, reloadOnChange: true
      );
    }
    

    https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.jsonconfigurationextensions

    【讨论】:

      【解决方案2】:

      我认为您正在寻找使用CreateDefaultBuilder。

      https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/web-host?view=aspnetcore-6.0

      那个将自动使用appsettings.{Environment}.json(有关它在该链接上的作用的更多详细信息。

      【讨论】:

        猜你喜欢
        • 2021-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-15
        • 2017-12-14
        • 2019-05-24
        • 2016-06-21
        • 2020-02-29
        相关资源
        最近更新 更多