I am using RestSharp v107.
I want to update Iteration Path of a test case. I am able to update it with Postman but using RestSharp I am getting "BAD Request" - "You must pass a valid patch document in the body of the request."
Azure Devops Update Work Item Rest API
My Code:
var client = new RestClient(@"https://dev.azure.com/krakhil/AkhilProject/_apis/wit/workitems/25?api-version=6.1-preview.3&Authorization=Basic BASE64PATSTRING");
client.Authenticator = new HttpBasicAuthenticator("", "My_PAT_I_HAVE_GENERATED");
var request = new RestRequest();
request.AddHeader("Content-Type", "application / json - patch json");
var body = @"[
" "\n"
@" {
" "\n"
@" ""op"": ""add"",
" "\n"
@" ""path"": ""/fields/System.IterationPath"",
" "\n"
@" ""value"": ""AkhilProject\\Sprint 1""
" "\n"
@" }
" "\n"
@"]";
request.AddParameter("application/json-patch json", body, ParameterType.RequestBody);
var response = client.PatchAsync(request).Result;
I have tried with "AddJSONBody", ExecuteAsync - with respective changes. Still no help.
CodePudding user response:
Sometimes it helps to just read the documentation.
All you needed to do is:
var request = new RestRequest()
.AddStringBody(body, "application/json-patch json");
CodePudding user response:
RestSharp working code - as per input from Alexey Zimarev
var client = new RestClient(@"https://dev.azure.com/krakhil/AkhilProject/_apis/wit/workitems/25?api-version=6.1-preview.3");
client.Authenticator = new HttpBasicAuthenticator("", "YOUR PAT");
var request = new RestRequest();
request.AddHeader("Content-Type", "application/json-patch json");
var body = @"[
" "\n"
@" {
" "\n"
@" ""op"": ""add"",
" "\n"
@" ""path"": ""/fields/System.IterationPath"",
" "\n"
@" ""value"": ""AkhilProject\\Sprint 1""
" "\n"
@" }
" "\n"
@"]";
request.AddStringBody(body, DataFormat.Json);
var response = client.PatchAsync(request).Result;
Working code using HTTP Client
string personalaccesstoken = "MY_PAT";
string organisation = "krakhil";
string project = "AkhilProject";
using HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
var obj = new[] { new { from = (string?)null, op = "add", path = "/fields/System.IterationPath", value = "AkhilProject\\Sprint 1" } };
string serialisedObj = System.Text.Json.JsonSerializer.Serialize(obj);
var content = new StringContent(
serialisedObj,
Encoding.UTF8,
"application/json-patch json");
HttpResponseMessage response = client.PatchAsync($"https://dev.azure.com/{organisation}/{project}/_apis/wit/workitems/25?api-version=6.1-preview.3",content).Result;
response.EnsureSuccessStatusCode();
string responseBody = response.Content.ReadAsStringAsync().Result;