我正在尝试根据Microsoft document使用TFS API更新TFS上的工作项的字段。使用页面上列出的示例代码时,api“更新工作项”有问题,响应的返回状态代码为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;
}
}
}
答案 0 :(得分:0)
您使用的是错误的mediaType,它应该是' application / json-patch + json '不是' application / json'。
var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json-patch+json");
在代码示例中,它已经注意到了您:
// mediaType需要是application / json-patch + json才能进行补丁调用
您正在调用Patch调用,因此请将mediaType更改为application/json-patch+json
。