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

如何用C#向VSTS创建发布API发起POST请求?

改造C#代码以向VSTS Release API发送POST请求

Got it, let's walk through how to modify your existing C# code to send a POST request to the VSTS Release API. Here's a step-by-step breakdown and the full updated code:

第一步:准备依赖

首先,你需要安装Newtonsoft.Json NuGet包(也叫Json.NET),用来把C#对象序列化为符合要求的JSON请求体。可以通过NuGet包管理器或者命令行安装:

Install-Package Newtonsoft.Json

第二步:定义请求体对应的实体类

为了更规范地构造请求体(避免直接拼接JSON字符串容易出错),我们先定义和API请求结构匹配的C#类:

public class ReleaseRequest
{
    public int definitionId { get; set; }
    public string description { get; set; }
    public List<Artifact> artifacts { get; set; }
    public bool isDraft { get; set; }
    public string reason { get; set; }
    public object manualEnvironments { get; set; }
}

public class Artifact
{
    public string alias { get; set; }
    public InstanceReference instanceReference { get; set; }
}

public class InstanceReference
{
    public string id { get; set; }
    public object name { get; set; }
}

第三步:改造原有的代码

我们会把原来的GetProjects方法改成CreateRelease,替换GET请求为POST,同时构造请求体并发送:

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

class Program
{
    // 把async void改成async Task,避免控制台程序提前退出
    public async Task CreateRelease()
    {
        try
        {
            var personalaccesstoken = "PAT"; // 替换成你的PAT
            var apiUrl = "https://fabrikam.vsrm.visualstudio.com/MyFirstProject/_apis/release/releases?api-version=4.1-preview.6";

            using (HttpClient client = new HttpClient())
            {
                // 设置请求头,和原来的GET请求一致
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", 
                    Convert.ToBase64String(Encoding.ASCII.GetBytes($":{personalaccesstoken}")));

                // 构造请求体对象
                var releaseRequest = new ReleaseRequest
                {
                    definitionId = 1,
                    description = "Creating Sample release",
                    artifacts = new List<Artifact>
                    {
                        new Artifact
                        {
                            alias = "Fabrikam.CI",
                            instanceReference = new InstanceReference
                            {
                                id = "2",
                                name = null
                            }
                        }
                    },
                    isDraft = false,
                    reason = "none",
                    manualEnvironments = null
                };

                // 把对象序列化为JSON字符串
                string jsonBody = JsonConvert.SerializeObject(releaseRequest);
                // 创建请求内容,指定媒体类型为application/json
                var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

                // 发送POST请求(替换原来的GetAsync)
                using (HttpResponseMessage response = await client.PostAsync(apiUrl, content))
                {
                    response.EnsureSuccessStatusCode(); // 如果请求失败会抛出异常
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Release created successfully! Response:");
                    Console.WriteLine(responseBody);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error occurred: {ex.ToString()}");
        }
    }

    // 使用async Main(需要C# 7.1及以上版本)
    static async Task Main(string[] args)
    {
        Program prog = new Program();
        await prog.CreateRelease();
    }
}

关键改造点说明

  • 替换请求方法:把client.GetAsync()换成client.PostAsync(),并传入构造好的请求内容
  • 请求体构造:用强类型对象代替直接写JSON,通过Json.NET序列化保证格式正确
  • 异步改进:把async void改成async Task,并使用async Main来等待异步操作完成(避免控制台程序在请求完成前退出)
  • 请求内容类型:创建StringContent时指定"application/json"媒体类型,确保API能正确解析请求体

如果你的项目不支持C# 7.1+的async Main,可以把Main方法改成这样:

static void Main(string[] args)
{
    Program prog = new Program();
    prog.CreateRelease().GetAwaiter().GetResult();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:59:34