使用有关更新工作项的 TFS API 时出错(HTTP 状态 400)

Error when using TFS API concerning updating work items( HTTP Status 400 )

我正在尝试根据 Microsoft document 使用 TFS API 更新 TFS 上工作项的字段。 api "Update work items" 使用页面列出的示例代码时有问题,响应的返回状态码是400。无论我做什么,状态码总是400,可以谁能帮帮我?

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;



public void UpdateWorkItemUpdateField()
{
   string _personalAccessToken = "xxxxxxxxxxxxxx";
   string _credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", _personalAccessToken)));
   string _id = "111";

   Object[] patchDocument = new Object[3];

   patchDocument[0] = new { op = "test", path = "/rev", value = "1" };
   patchDocument[1] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Priority", value = "2" };
   patchDocument[2] = new { op = "add", path = "/fields/System.History", value = "Changing priority" };

  using (var client = new HttpClient())
   {
       client.DefaultRequestHeaders.Accept.Clear();
   client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
   client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials);

   var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json"); // mediaType needs to be application/json-patch+json for a patch call

  var method = new HttpMethod("PATCH");
   var request = new HttpRequestMessage(method, "https://accountname.visualstudio.com/_apis/wit/workitems/" + _id + "?api-version=2.2") { Content = patchValue };
   var response = client.SendAsync(request).Result;

   if (response.IsSuccessStatusCode)
   {
       var result = response.Content.ReadAsStringAsync().Result;
   }
   }
}

您使用了错误的媒体类型,应该是“application/json-patch+json”而不是 'application/json'。

var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json-patch+json");

在代码示例中,它已经注意到你:

// mediaType needs to be application/json-patch+json for a patch call

您正在调用 Patch 调用,因此请将 mediaType 更改为 application/json-patch+json