gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:18:53 25 4
gpt4 key购买 nike

我有一个 .net core 3.1 后台 worker ,它作为后台 worker 安装在 ubuntu 中。但它无法获取我需要进行多配置的环境变量的值,这就是为什么如您所见,主机环境的值是默认值,即 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 后台 worker 中的代码。

 _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}");

在 cmd 上输出。

enter image description here

enter image description here

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");
});

最佳答案

我已经知道了。我在 .Service 文件上添加了 Environment=DOTNET_ENVIRONMENT=Development。

关于c# - 为什么ubuntu中的NET Core 3.1 BackgroundWorker无法访问环境变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59925982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com