假设我有一个具有以下定义的构建管道:
parameters:
- name: "BoxNames"
displayName: 'List of box names'
type: object
default:
- name1
- name2
- name: 'id'
displayName: 'subscrption id'
type: string
default: 'xxxx'
values:
- xxxx
- yyyy
现在我尝试通过带有以下请求正文的 REST API 在 C# 中对该管道的构建进行排队:
var requestBody = new
{
definition = new
{
id = 234,
},
project = new
{
id = xxxx
},
sourceBranch = "main",
templateParameters = new
{
BoxNames = new List<string> { "name1" },
id = "yyyy"
}
};
这是为我排队构建,但它将 templateParameters 作为默认参数,而不是我在请求正文中发送的参数。
我有另一个带有字符串参数且没有列表值的管道,即通过相同的方式选择正确的参数。
这里可能出现什么问题?
我按照你的yaml和C#代码片段,输出了
requestbody
和response content
,它会报告错误Unable to convert from Array to String. Value: Array"
。
您在 yaml 中为参数
object
定义了 BoxNames
类型,但在 C# 脚本中,它是字符串格式。
要修复错误,您可以直接在请求正文中定义值:
templateParameters = new
{
BoxNames = "name6",
id = "yyyy"
}
完整的 C# 脚本:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net.Http.Headers;
class Program
{
static async Task Main(string[] args)
{
var personalAccessToken = "PAT";
string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalAccessToken)));
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
var requestBody = new
{
definition = new { id = "410" },
sourceBranch = "refs/heads/main",
templateParameters = new
{
BoxNames = "name6",
id = "yyyy"
}
};
var serializedRequestBody = JsonConvert.SerializeObject(requestBody);
Console.WriteLine($"Request Body: {serializedRequestBody}");
var content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
var url = $"https://dev.azure.com/{org}/{project}/_apis/build/builds?api-version=7.1-preview.7";
var response = await client.PostAsync(url, content);
Console.WriteLine($"Response Status Code: {response.StatusCode}");
Console.WriteLine($"Response Content: {await response.Content.ReadAsStringAsync()}");
response.EnsureSuccessStatusCode();
Console.WriteLine("Build queued successfully.");
}
}
}
devops yaml:
trigger: none
parameters:
- name: "BoxNames"
displayName: 'List of box names'
type: object
default:
- name1
- name2
- name: 'id'
displayName: 'subscrption id'
type: string
default: 'xxxx'
values:
- xxxx
- yyyy
pool:
vmImage: ubuntu-latest
steps:
- script: |
echo ${{ parameters.BoxNames }}
echo ${{ parameters.id }}
displayName: 'Run a one-line script'
C#触发结果: