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

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

我正在开发一个在 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 核心 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);
            }
        }