【发布时间】:2022-07-08 02:01:49
【问题描述】:
我正在尝试通过 API 创建工作项,但出现以下错误:
{
"innerException": null,
"message": "You must pass a valid patch document in the body of the request.",
"typeName": "Microsoft.VisualStudio.Services.Common.VssPropertyValidationException, Microsoft.VisualStudio.Services.Common",
"typeKey": "VssPropertyValidationException",
"errorCode": 0,
"eventId": 3000
}
代码:
public class Chamados
{
public async Task<string> CriaChamadoDevOps()
{
string organizacao = "xxx";
string departamento = "xxx";
string tipoWorkItem = "xxx";
string authToken = "xxx";
// Montando a Requisição
string urlReq = "https://dev.azure.com/" + organizacao + "/" + departamento + "/_apis/wit/workitems/$" + tipoWorkItem + "?api-version=6.0";
var client = new RestClient(urlReq);
var request = new RestRequest(urlReq, Method.Post);
// Montando Headers
request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "", authToken))));
request.AddHeader("Content-Type", "application/json-patch+json; charset=utf-8");
var body = new JArray {
new JObject {
{ "op", "add" },
{ "path", "/fields/System.Title" },
{ "value", "Assunto Teste" }
},
new JObject {
{ "op", "add" },
{ "path", "/fields/System.State" },
{ "value", "To do" }
},
new JObject {
{ "op", "add" },
{ "path", "/fields/System.Description" },
{ "value", "Descricao Teste" }
},
};
//request.AddBody(body);
request.AddParameter("application/json-patch+json; charset=utf-8", body, ParameterType.RequestBody);
Console.WriteLine(body);
RestResponse response = await client.ExecuteAsync(request);
dynamic resposta = JsonConvert.DeserializeObject(response.Content);
return resposta.ToString();
}
}
当我通过 Postman 对其进行测试时,它可以工作。
这就是我将正文发送到请求的方式: (来自 Console.WriteLine(body) 的输出;)
[
{
"op": "add",
"path": "/fields/System.Title",
"value": "Assunto Teste"
},
{
"op": "add",
"path": "/fields/System.State",
"value": "To do"
},
{
"op": "add",
"path": "/fields/System.Description",
"value": "Descricao Teste"
}
]
我还尝试用“request.AddBody()”方法替换“request.AddParameter()”。
【问题讨论】:
-
当您尝试将
var request行中的 Method.Post 更改为 Method.Patch 或 Method.Put 时会发生什么 -
你使用了正确的 Http 动词吗?您是否设置了正确的内容标题,例如“application/json”?