Search code examples
c#visual-studioapitfstfs-sdk

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


I am trying to update a field of a work-item on TFS using the TFS API according to the Microsoft document. There is something wrong with the api "Update work items" when using the sample code listed on the page, the returning status code of the response is 400. No matter what I did, the status code is always 400, can anyone please give me some help?

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;
   }
   }
}

Solution

  • You are using a wrong mediaType, it should be 'application/json-patch+json' not 'application/json'.

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

    In the code sample, it has already noted you:

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

    You're invoke a Patch call, so please change the mediaType to application/json-patch+json.