Search code examples
c#azure-devopsyaml

How to trigger a pipeline from particular branch using c#


I have implemented the below code to trigger the pipeline. Here pipeline is triggering from master branch instead of target branch even though Azure dev has target branch. There is no default branch triggering in the pipeline yaml. what other configurations need to change to trigger the pipeline w.r.t target branch instead of master branch

try
{
    using (HttpClient client = new HttpClient())
    {
        // Set the base URL for the Azure DevOps REST API
        client.BaseAddress = new Uri($"{organizationUrl}/{project}/_apis/pipelines/{pipelineId}/");

        // Set the authorization header using the personal access token
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($":{personalAccessToken}")));

        // Set the content type header
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        string requestBody = $"{{\"definition\": {{\"id\": {pipelineId}}}, \"sourceBranch\": \"refs/heads/{targetBranch}\"}}";
        
        // Define the request body with run parameters, including the branch name
        var content = new StringContent(requestBody, Encoding.UTF8, "application/json");

        // Debugging output
        Console.WriteLine($"Request Payload: {requestBody}");
        // Make a POST request to trigger the pipeline run
        HttpResponseMessage response = await client.PostAsync("runs?api-version=6.0-preview.1", content);

        // Check if the request was successful
        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine("Pipeline run triggered successfully.");
        }
        else
        {
            Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"Response body: {responseBody}");
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Exception: {ex.Message}");
}

Solution

  • The cause of the issue is that the request body is not correct.

    You can use the following Request body to Run the Rest API to set the trigger branch:

    {"resources": {"repositories": {"self": {"refName": "refs/heads/BranchName"}}}}
    

    Here is the C# Example:

    try
    {
        using (HttpClient client = new HttpClient())
        {
            // Set the base URL for the Azure DevOps REST API
            client.BaseAddress = new Uri($"{organizationUrl}/{project}/_apis/pipelines/{pipelineId}/");
    
            // Set the authorization header using the personal access token
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($":{personalAccessToken}")));
    
            // Set the content type header
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
           
            
            // Define the request body with run parameters, including the branch name
            var content = new StringContent("{\"resources\": {\"repositories\": {\"self\": {\"refName\": \"refs/heads/branchname\"}}}}", Encoding.UTF8, "application/json");
    
            // Debugging output
            Console.WriteLine($"Request Payload: {requestBody}");
            // Make a POST request to trigger the pipeline run
            HttpResponseMessage response = await client.PostAsync("runs?api-version=6.0-preview.1", content);
    
            // Check if the request was successful
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Pipeline run triggered successfully.");
            }
            else
            {
                Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"Response body: {responseBody}");
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Exception: {ex.Message}");
    }
    

    Note: Each pipeline is based on a specific YML file. If you call the rest api to run the pipeline based on one branch of the repo, you must make sure there is a same name YML file in the branch.

    Result:

    enter image description here