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

Azure DevOps Rest API创建迭代失败:400无效请求问题排查

Azure DevOps API创建迭代返回400错误的排查与修复

你调用API获取项目迭代正常,但创建新迭代返回400错误,问题出在代码操作上,API本身没有问题,具体错误点和修复方案如下:

  • 变量名不匹配:你定义的请求体变量是$body,但调用Add-Iteration函数时传入的是未定义的$iterationData,导致POST的请求内容无效。
  • 缺少必要请求头:发送JSON格式请求体时,必须添加Content-Type: application/json请求头,否则服务器无法正确解析你的请求。
  • 可选优化:使用ConvertTo-Json时,默认序列化深度为2,虽然当前结构没问题,但如果后续有更深嵌套的结构,建议显式指定-Depth参数(比如-Depth 10)避免序列化截断。

修正后的完整代码:

# Variables
$organization = "x"
$project = "y"
$pat = "z"

$baseUrl = "https://dev.azure.com/$organization/$project/_apis/work/teamsettings/iterations?api-version=6.0"

# authentication
$headers = @{
    Authorization = "Basic " + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($pat)"))
    "Content-Type" = "application/json"  # 添加Content-Type头
}

# HTTP GET
$response = Invoke-RestMethod -Uri $baseUrl -Method Get -Headers $headers

# list iterations
$response.value | ForEach-Object {
    Write-Output "Iteration Name: $($_.name)"
    Write-Output "Start Date: $($_.attributes.startDate)"
    Write-Output "End Date: $($_.attributes.finishDate)"
    Write-Output "Path: $($_.path)"
    Write-Output "----------------------------------"
}

# data for new iteration
$body = @{
    name = "blabla"
    attributes = @{
        startDate = (Get-Date).AddDays(1).ToString("yyyy-MM-ddTHH:mm:ssZ")
        finishDate = (Get-Date).AddDays(14).ToString("yyyy-MM-ddTHH:mm:ssZ")
    }
} | ConvertTo-Json -Depth 10  # 显式指定序列化深度

# HTTP POST
function Add-Iteration {
    param (
        [string]$url,
        [hashtable]$headers,
        [string]$body
    )
    try {
        $response = Invoke-RestMethod -Uri $url -Method Post -Headers $headers -Body $body
        Write-Output "Iteration successfully added:"
        Write-Output $response
    }
    catch {
        Write-Output "Error adding iteration:"
        Write-Output $_.Exception.Message
        # 可选:打印更详细的错误信息,便于排查
        Write-Output "Response content: $($_.Exception.Response.Content.ReadAsStringAsync().Result)"
    }
}

# add iteration - 修正变量名,传入$body
Add-Iteration -url $baseUrl -headers $headers -body $body

另外,建议保留catch块中详细错误内容的打印逻辑,这样如果还有其他问题,能看到服务器返回的具体错误描述,进一步排查。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 18:14:52