Search code examples
asp.net-core.net-coregitlabgitlab-cigitlab-api

Update .gitlab-ci.yml file in GitLab using Gitlab API in C#


I am working on a project that has a file .gitlab-ci.yml in master branch. I am trying to update that .yml file using gitlab api (https://docs.gitlab.com/ee/api/commits.html#create-a-commit-with-multiple-files-and-actions) but using it from a asp.net core 5 application.

Here is my try. But I am getting 400 bad request error. Kindly help to find out what is wrong I am doing here.

public IActionResult Update()
        {
            var url = $"{ProjectUrl}/{ProjectId}/repository/commits/";

            var httpRequest = (HttpWebRequest)WebRequest.Create(url);
            httpRequest.Method = "PUT";

            httpRequest.Headers["PRIVATE-TOKEN"] = ClientSecret;
            httpRequest.ContentType = "application/json";

            var str =
                @"{'branch': 'master',
                        'commit_message': 'some commit message',
                        'actions': [
                        {
                            'action': 'update',
                            'file_path': '.gitlab-ci.yml',
                            'content': 'some content'
                        }
                    }";
            var data = str;

            using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
            {
                streamWriter.Write(data);
            }

            var httpResponse = (HttpWebResponse)httpRequest.GetResponse(); // I'm getting 400 Bad request error here
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();

                // rest of the code goes here
            }

            return View();
        }


Solution

  • Well after rewriting the code, finally I am able to make it works. Posting my solution here in a hope that someone will be benefited from this. Cheers!

            using (var httpClient = new HttpClient())
            {
                using (var request = new HttpRequestMessage(new HttpMethod("PUT"), "https://ProjectUrl/api/v4/projects/projectid/repository/%2Egitlab%2Dci.yml"))
                {
                    request.Headers.TryAddWithoutValidation("PRIVATE-TOKEN", "<your_private_token>");
    
                    request.Content = new StringContent("{\"branch\": \"master\", \"author_email\": \"[email protected]\", \"author_name\": \"user\", \n    \"content\": \"some content\", \"commit_message\": \"update file\"}");
                    request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
    
                    var response = await httpClient.SendAsync(request);
                }
            }