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

如何通过Azure DevOps .NET客户端库传递templateParameters启动管道运行?

解决方案

1. 切换到适配YAML管道的客户端库

你当前使用的Microsoft.TeamFoundationServer.ExtendedClient主要针对传统TFS构建体系,而templateParameters是Azure DevOps YAML管道的专属特性,需要替换为Microsoft.Azure.DevOps.Client NuGet包,该包内置PipelinesHttpClient,可直接调用Pipelines/Runs API。

安装命令:

Install-Package Microsoft.Azure.DevOps.Client

2. 使用PipelinesHttpClient传递templateParameters

通过PipelinesHttpClient的QueuePipelineRunAsync方法,配合RunCreateRequest类设置模板参数,示例代码如下:

using Microsoft.VisualStudio.Services.WebApi;
using Microsoft.Azure.DevOps.Pipelines.WebApi;

// 初始化连接(假设你已有VssConnection实例)
var pipelinesClient = connection.GetClient<PipelinesHttpClient>();

// 构造管道运行请求
var runRequest = new RunCreateRequest
{
    Definition = new DefinitionReference { Id = buildDefinition.Id },
    SourceBranch = branchName,
    TemplateParameters = new Dictionary<string, object>
    {
        { "ParameterName1", "ParameterValue1" },
        { "ParameterName2", 123 }
    }
};

// 提交管道运行
var run = await pipelinesClient.QueuePipelineRunAsync(runRequest, project.Name);

3. 手动调用HTTP API(备选方案)

如果因版本限制无法使用上述客户端,可通过Azure DevOps客户端基类VssHttpClientBase手动发送HTTP请求,直接调用Pipelines/Runs API端点:

using Microsoft.VisualStudio.Services.WebApi;
using System.Net.Http;
using System.Text.Json;

var httpClient = connection.GetClient<VssHttpClientBase>();

// 构造请求体
var requestBody = new
{
    definition = new { id = buildDefinition.Id },
    sourceBranch = branchName,
    templateParameters = new
    {
        ParameterName1 = "ParameterValue1",
        ParameterName2 = 123
    }
};

var jsonContent = new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json");

// 发送POST请求到Pipelines/Runs API
var response = await httpClient.SendAsync(
    new HttpRequestMessage(HttpMethod.Post, $"_apis/pipelines/runs?api-version=7.1-preview.1")
    {
        Content = jsonContent
    },
    project.Name
);

response.EnsureSuccessStatusCode();
var runResult = await response.Content.ReadFromJsonAsync<Run>();

注意:API版本可根据你的Azure DevOps服务器版本调整,选择对应兼容的预览版或稳定版即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:38:30