使用 C# 中的 Gitlab API 更新 GitLab 中的 .gitlab-ci.yml 文件

问题描述

我正在开发一个在 master 分支中有一个文件 .gitlab-ci.yml 的项目。我正在尝试使用 gitlab api (https://docs.gitlab.com/ee/api/commits.html#create-a-commit-with-multiple-files-and-actions) 更新该 .yml 文件,但从 asp.net core 5 应用程序使用它。

这是我的尝试。但是我收到 400 个错误的请求错误。请帮助找出我在这里做错了什么。

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();
        }

解决方法

在重写代码之后,我终于能够让它工作了。在这里发布我的解决方案,希望有人能从中受益。干杯!

        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\": \"user@email.com\",\"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);
            }
        }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...