我正在創建一個 Powershell 腳本,它將使用 Azure DevOps REST API 更新作業項中的特定欄位。我將請求正文作為哈希表,然后在發出請求時轉換為 JSON。
發出請求時出現此錯誤:
{"$id":"1","innerException":null,"message":"You must pass a valid patch document in the body of the
| request.","typeName":"Microsoft.VisualStudio.Services.Common.VssPropertyValidationException,
| Microsoft.VisualStudio.Services.Common","typeKey":"VssPropertyValidationException","errorCode":0,"eventId":3000}
這是我的 Powershell 腳本:
$url = 'https://dev.azure.com/orgname/projectname/_apis/wit/workitems/9999?api-version=7.1-preview.3'
$Token = 'PAT generated in DevOps'
$body = @(
@{
op = "add"
path = "/fields/Microsoft.VSTS.Build.IntegrationBuild"
value = "v.09-09-1999"
}
)
$AzureAuthHeader = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $Token)))
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", ("Basic {0}" -f $AzureAuthHeader))
$headers.Add("Content-Type", "application/json-patch json")
$response = Invoke-RestMethod -Uri $url -Method PATCH -Headers $headers -Body ($body|ConvertTo-Json -Depth 2)
我正在將哈希表轉換為 JSON,請求正文格式遵循此示例。我不確定是什么問題。
uj5u.com熱心網友回復:
使用相同的 Powershell 腳本進行測驗并得到相同的問題。
使用 format$body|ConvertTo-Json -Depth 2時,json 值如下:
{
"path": "/fields/Microsoft.VSTS.Build.IntegrationBuild",
"op": "add",
"value": "v.09-09-1999"
}
正文與官方檔案中的示例不同。
此問題的原因是,如果您有一個陣列物件,其中只有一個專案管道到 ConvertTo-Json 會將其視為單個物件(而不是陣列)。
預期的格式是一個陣列。
例如:
[
{
"path": "/fields/Microsoft.VSTS.Build.IntegrationBuild",
"op": "add",
"value": "v.09-09-1999"
}
]
要解決此問題,您可以更改為使用以下格式:
ConvertTo-Json -InputObject $body
這是 PowerShell 示例:
$url = 'https://dev.azure.com/orgname/projectname/_apis/wit/workitems/9999?api-version=7.1-preview.3'
$Token = 'PAT generated in DevOps'
$body = @(
@{
op = "add"
path = "/fields/Microsoft.VSTS.Build.IntegrationBuild"
value = "v.09-09-1999"
}
)
$AzureAuthHeader = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $Token)))
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", ("Basic {0}" -f $AzureAuthHeader))
$headers.Add("Content-Type", "application/json-patch json")
$response = Invoke-RestMethod -Uri $url -Method PATCH -Headers $headers -Body (ConvertTo-Json -InputObject $body)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/488539.html
