使用 C# 和 Azure DevOps Rest API 创建工作项

7
我无法使用Azure DevOps REST API按照工作项-创建中的说明创建工作项。

请求:

https://dev.azure.com/{organization}/MyTestProject/_apis/wit/workitems/$Task?api-version=6.0-preview.3

Request Body:
[
  {
    "op": "add",
    "path": "/fields/System.Title",
    "value": "Task2"
  }
]

获取响应的代码(请注意,该代码适用于所有其他POST请求):

using (HttpResponseMessage response = client.SendAsync(requestMessage).Result)
      {
         response.EnsureSuccessStatusCode();
         JsonResponse = await response.Content.ReadAsStringAsync();
      }

Response: 400

有人可以提供建议吗?


1
你是否尝试按照文档中的说明,向JSON中添加"from": null元素?你是否将内容类型设置为application/json-patch+json,如文档所示? - Daniel Mann
2个回答

9

可能看到您的完整示例会更有帮助。不过,以下是一个使用 Newtonsoft.Json 的工作示例(不要忘记创建您的 PAT 创建个人访问令牌):

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

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            string PAT = "<personal access token>"; //https://learn.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=azure-devops&tabs=preview-page
            string requestUrl = "https://dev.azure.com/<my_org>/<my_project>/_apis/wit/workitems/$Task?api-version=5.0";
            try
            {
                List<Object> flds = new List<Object>
                {
                    new { op = "add", path = "/fields/System.Title", value = "Title" }
                };


                string json = JsonConvert.SerializeObject(flds);

                HttpClientHandler _httpclienthndlr = new HttpClientHandler();

                using (HttpClient client = new HttpClient(_httpclienthndlr))
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(
                System.Text.ASCIIEncoding.ASCII.GetBytes(
                string.Format("{0}:{1}", "", PAT))));


                    var request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUrl)
                    {
                        Content = new StringContent(json, Encoding.UTF8, "application/json-patch+json")
                    };

                    HttpResponseMessage responseMessage = client.SendAsync(request).Result;
                }

            }
            catch (Exception ex)
            {

            }
        }
    }
}

此外,您可以考虑使用Azure DevOps和TFS的.NET客户端库。以下是示例:使用.NET客户端库在Azure DevOps Services中创建缺陷


嗨,Shamrai,这里有一个类似的问题,你可能能够回答。谢谢!https://dev59.com/sb7pa4cB1Zd3GeqPrhuq - Patrick McElhaney
我们如何添加自定义字段? - Balanjaneyulu K

6

必须使用 application/json-patch+json。


非常感谢您在这里分享解决方案。如果您能接受此解决方案,那么其他人就可以直接知道这个解决方案可行 :-) - Mengdi Liang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接