Set lease for build with Azure DevOps API in C#

404 Views Asked by At

If the right condition I will make a call to my Azure DevOps server, to set a build to not be deleted.

I followed: https://learn.microsoft.com/en-us/rest/api/azure/devops/build/leases/add?view=azure-devops-rest-6.0

I have some C# code where I try to set retain for a specific build. But I get bad request in the HttpResponse. I do several other calls to the API also due the bad request I feel confidence it isn't permissions.

I have added my code though anonymized.

using (var httpClient = new HttpClient(new HttpClientHandler()))
{
  httpClient.DefaultRequestHeaders.Accept.Add(new 
    MediaTypeWithQualityHeaderValue("application/json"));
    
  httpClient.DefaultRequestHeaders.Authorization = new 
    AuthenticationHeaderValue("Basic", personalAccessToken);
    
  JObject postBody = new JObject
  {
    { "daysValid", 100 },
    { "ownerId", "[email protected]" },
    { "definitionId", 2222 },
    { "protectPipeline", true },
    { "runId", 4444 }
  };
    
  HttpContent content = new StringContent(postBody.ToString(), 
    Encoding.UTF8, "application/json");
    
  using HttpResponseMessage response = await 
httpClient.PostAsync($"https://dev.azure.com/{organization}/{project}/_apis/build/retention/leases?api-version=6.0-preview.1",
                            content).ConfigureAwait(false);
  if (!response.IsSuccessStatusCode)
  {
  }
}
1

There are 1 best solutions below

0
On

The solution was actually quite simple. At least when you know it. The content data I provided should be in an array, so after I changed to:

JArray array = new JArray { postBody };

HttpContent content = new StringContent(JsonConvert.SerializeObject(array), Encoding.UTF8, "application/json");

It worked perfectly and I can now see my new lease is added to the build.