问题描述
我正在开发一个在 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);
}
}