通过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
相关产品推荐
相关产品推荐

