You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8.0程序通过Azure Pipeline调用时无法读取appsettings配置

.NET 8控制台应用通过Azure经典管道PowerShell任务运行时无法加载appsettings.json

我有一个部署到服务器的.NET 8.0控制台应用,以下场景运行均正常:

  • 本地直接运行
  • 在服务器上双击可执行文件运行
  • 在服务器手动执行PowerShell脚本启动应用

但通过Azure经典管道的PowerShellOnTargetMachines@3任务调用服务器上的PowerShell脚本启动时,首次从appsettings.json读取配置值就返回null,抛出异常:

Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString')


相关代码与配置

Azure经典管道任务YAML

steps:
- task: PowerShellOnTargetMachines@3
  displayName: 'Run PowerShell on Target Machines'
  inputs:
    Machines: 127.0.0.1
    UserName: 'Domain\admin-geezer'
    UserPassword: '$(UserPassword)'
    ScriptType: FilePath
    ScriptPath: 'C:\Program Files\App-Location\App.ps1'

服务器上的PowerShell脚本

& "dotnet" "C:\Program Files\App-Location\App.exe"

.NET应用代码(Program.cs)

var builder = Host.CreateApplicationBuilder(args);
...
var connectionString = builder.Configuration["ServiceBus:ConnectionString"];

问题原因

核心是工作目录不一致:通过Azure管道任务执行脚本时,默认工作目录并非应用程序所在目录(C:\Program Files\App-Location\),而是管道任务的临时工作目录。.NET默认从当前工作目录加载appsettings.json,而非可执行文件所在目录,因此找不到配置文件导致读取值为null。


解决方案

方案1:在PowerShell脚本中切换到应用目录

修改服务器上的PowerShell脚本,先切换到应用所在目录再启动:

Set-Location "C:\Program Files\App-Location\"
& "dotnet" ".\App.exe"

方案2:在.NET代码中指定配置文件路径

构建配置时明确指定appsettings.json的绝对路径(基于可执行文件所在目录):

using System.Reflection;
using System.IO;

var exeDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var builder = Host.CreateApplicationBuilder(args);
builder.Configuration.AddJsonFile(Path.Combine(exeDirectory, "appsettings.json"), optional: false, reloadOnChange: true);
...
var connectionString = builder.Configuration["ServiceBus:ConnectionString"];

方案3:在管道任务中指定工作目录

在PowerShellOnTargetMachines@3任务参数中添加工作目录配置:

steps:
- task: PowerShellOnTargetMachines@3
  displayName: 'Run PowerShell on Target Machines'
  inputs:
    Machines: 127.0.0.1
    UserName: 'Domain\admin-geezer'
    UserPassword: '$(UserPassword)'
    ScriptType: FilePath
    ScriptPath: 'C:\Program Files\App-Location\App.ps1'
    WorkingDirectory: 'C:\Program Files\App-Location\'

内容的提问来源于stack exchange,提问作者Billy Ray Valentine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 16:07:46