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

通过API关联工作项至Azure DevOps Pull Request遇错误求助

问题排查与修复

核心问题:ArtifactLink的URL格式错误

Azure DevOps工作项关联Pull Request时,ArtifactLink类型的URL不能使用REST API的端点地址,必须使用Azure DevOps专属的vstfs URI格式,而非你当前使用的https://dev.azure.com/.../pullRequests/12345这类API链接。

额外问题:变量名不匹配

你的代码中定义了变量$prapi1存储PR的API地址,但JSON补丁中引用的是未定义的$pr变量,这会导致URL替换错误(即使你实际代码中是笔误,也需要修正)。

修复步骤

1. 修正变量名

将JSON中的$pr替换为$prapi1(确保变量名一致):

$json = @"
[ {
  "op": "add",
  "path": "/relations/-",
  "value": {
    "rel": "ArtifactLink",
    "url": "$prapi1",
    "attributes": { "name": "pull request" }
  }
} ]
"@

2. 替换为正确的vstfs URI格式

将PR的API地址替换为vstfs格式的URI,格式如下:

vstfs:///Git/PullRequestId/{ProjectId}/{RepositoryId}/{PullRequestId}

如何获取ProjectId和RepositoryId?

  • ProjectId:可在项目设置的Overview页面查看,或调用项目列表API获取。
  • RepositoryId:可在仓库的Settings页面查看,或调用仓库列表API获取。

修正后的示例代码

假设你已获取到$projectId、$repoId和$pullRequestId,代码如下:

$requestUri = "https://dev.azure.com/$org/$project/_apis/wit/workitems/12345?api-version=4.1"
# 构造正确的vstfs URI
$prVstfsUri = "vstfs:///Git/PullRequestId/$projectId/$repoId/12345"

$json = @"
[ {
  "op": "add",
  "path": "/relations/-",
  "value": {
    "rel": "ArtifactLink",
    "url": "$prVstfsUri",
    "attributes": { "name": "pull request" }
  }
} ]
"@

$response = Invoke-RestMethod -Uri $requestUri -Headers $headers -ContentType "application/json-patch+json" -Method Patch -Body $json

另一种更可靠的方式:通过PR API获取关联链接

你也可以先调用Pull Request的API获取其工作项关联的正确链接格式,再用于工作项补丁:

# 先获取PR详情
$prDetails = Invoke-RestMethod -Uri "https://dev.azure.com/$org/$project/_apis/git/repositories/$repo/pullRequests/12345?api-version=4.1" -Headers $headers
# 提取正确的ArtifactLink URL
$prArtifactUrl = $prDetails._links.workItemRelations.href

然后将$prArtifactUrl用于JSON补丁中的url字段即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 21:33:12