为什么 ubuntu 中的 NET Core 3.1 BackgroundWorker 无法访问环境变量?

Why NET Core 3.1 BackgroundWorker in ubuntu can't access environment variables?

我有一个安装在 ubuntu 中的 .net core 3.1 后台工作程序作为后台工作程序。但是它无法获得我需要进行多配置的环境变量的值,这就是为什么你可以看到主机环境的值是默认值,即 Production。

我已经尝试过 hostenvironment.environmentname 和 Environment.GetEnvironmentVariable。

我的服务文件在/etc/systemd/

[Unit]
Description=TestService

[Service]
Type=notify
WorkingDirectory=/home/centos/TestService/
ExecStart=/usr/bin/dotnet /home/centos/TestService/WorkerService2.dll
User=centos

[Install]
WantedBy=multi-user.target

NET Core 3.1 后台工作者中的代码。

 _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            _logger.LogError("ERROR testing");
            _logger.LogInformation($"Hosting Enviornment: {_hostEnvironment.EnvironmentName}");
            _logger.LogInformation(_configuration["Test"]);
            var basePath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            var contentroothpath = _hostEnvironment.ContentRootPath;

            Console.WriteLine($"basepath = {basePath}");
            Console.WriteLine($"contentrootpath = {contentroothpath}");
            _logger.LogInformation($"basepath = {basePath}");
            _logger.LogInformation($"contentrootpath = {contentroothpath}");



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

            _logger.LogInformation($"ASPNETCORE_ENVIRONMENT = {environmentName}");
            _logger.LogInformation($"DOTNET_ENVIRONMENT = {environmentName2}");

命令输出。

program.cs

中的代码
 public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseSystemd()
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>();
                var basePath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                //NLog.LogManager.LoadConfiguration($"{basePath}/NLog.{hostContext.HostingEnvironment.ContentRootPath}.config");
            })
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile(
                    $"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);
                //NLog.LogManager.LoadConfiguration($"/home/centos/TestService/{hostingContext.HostingEnvironment.EnvironmentName}.config");
                //NLog.LogManager.LoadConfiguration($"{basePath}" +
                //    $"/NLog.{hostingContext.HostingEnvironment.EnvironmentName}.config");
            });

您需要访问 Main() 中的 HostBuilderContext 才能访问像这样的托管环境

 CreateHostBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;
                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

                if (env.IsDevelopment() || env.EnvironmentName.ToLower() == "dev")
                    config.AddJsonFile("appsettings.dev.json", optional: true, reloadOnChange: true);
                else if (env.IsStaging() || env.EnvironmentName.ToLower() == "stage")
                    config.AddJsonFile("appsettings.stage.json", optional: true, reloadOnChange: true);                    

                config.AddEnvironmentVariables();
            }).Build().Run();

此外,不要忘记添加环境变量

  • 在项目属性 launchSettings.json 中
  • 在 linux 上,使用命令 setx ASPNETCORE_ENVIRONMENT "Development" 并使用 echo ASPNETCORE_ENVIRONMENT
  • 检查环境设置是否正确

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:57993/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

我已经知道了。我在 .Service 文件上添加了环境=DOTNET_ENVIRONMENT=开发。