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

如何在Azure DevOps构建管道中运行已编译的.NET 7.0控制台应用

解决Linux构建代理上Azure DevOps管道运行.NET控制台应用失败的问题

问题背景

我们有一个可成功编译多个C#项目的Azure DevOps构建管道,其中包含一个执行特定功能的控制台应用,尝试通过以下YAML片段运行该应用:

- task: DotNetCoreCLI@2
  displayName: Run my.NET Console application
  continueOnError: false
  inputs:
    command: 'run'
    projects: '**/MyConsoleApp.csproj'
    arguments: '''--configuration $(BuildConfiguration)''' 

管道已将以下步骤设为第一步,确保构建代理预先安装指定.NET SDK:

- task: UseDotNet@2
  displayName: 'Use dotnet sdk'
  inputs:
    packageType: sdk
    version: 7.0.400
    installationPath: $(Agent.ToolsDirectory)/dotnet

错误与警告信息

运行后出现失败:

##[error]Error: The process '/opt/hostedtoolcache/dotnet/dotnet' failed with exit code 134

同时收到警告:

##[warning].NET 5 has some compatibility issues with older Nuget versions(<=5.7), so if you are using an older Nuget version(and not dotnet cli) to restore, then the dotnet cli commands (e.g. dotnet build) which rely on such restored packages might fail. To mitigate such error, you can either: (1) - Use dotnet cli to restore, (2) - Use Nuget version 5.8 to restore, (3) - Use global.json using an older sdk version(<=3) to build
Info: Azure Pipelines hosted agents have been updated and now contain .Net 5.x SDK/Runtime along with the older .Net Core version which are currently lts. Unless you have locked down a SDK version for your project(s), 5.x SDK might be picked up which might have breaking behavior as compared to previous versions.

解决方案

1. 修正dotnet run的参数格式

原YAML中arguments的引号嵌套错误,Linux环境下不需要额外单引号包裹参数,修改为:

arguments: '--configuration $(BuildConfiguration)'

额外的单引号会被当作参数的一部分传递,导致应用解析参数出错,引发退出码134。

2. 锁定.NET SDK版本

虽然已添加UseDotNet@2任务,但可通过global.json文件明确锁定SDK版本,避免代理默认使用.NET 5 SDK:
在项目根目录创建global.json文件并提交到仓库:

{
  "sdk": {
    "version": "7.0.400",
    "rollForward": "latestMinor"
  }
}

3. 改用发布后运行的方式

避免直接使用dotnet run,先发布应用再运行编译后的可执行文件,步骤如下:

  • 添加发布任务:
- task: DotNetCoreCLI@2
  displayName: Publish Console App
  inputs:
    command: 'publish'
    projects: '**/MyConsoleApp.csproj'
    arguments: '--configuration $(BuildConfiguration) --output $(Build.ArtifactStagingDirectory)/consoleapp'
    publishWebProjects: false
  • 添加运行发布产物的脚本任务:
- script: |
    chmod +x $(Build.ArtifactStagingDirectory)/consoleapp/MyConsoleApp
    $(Build.ArtifactStagingDirectory)/consoleapp/MyConsoleApp
  displayName: Run Published Console App

4. 统一使用dotnet restore进行包还原

如果管道中使用了NuGet任务而非dotnet restore,切换为dotnet restore任务,避免旧版本NuGet与.NET 7的兼容性问题:

- task: DotNetCoreCLI@2
  displayName: Restore NuGet Packages
  inputs:
    command: 'restore'
    projects: '**/*.csproj'

内容的提问来源于stack exchange,提问作者Arash

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 21:22:57