我已经阅读了Azure DevOPS REST API文档,并试图多次将其实现到我的Web应用程序,但无济于事。我没有使用REST API的经验,如果有人可以引导我朝正确的方向发展,我将不胜感激。
我正在尝试为Azure DevOps存储库创建POST请求,并希望通过API方法创建新的存储库。我已经阅读了有关此文档,但是我不知道如何在自己的项目中实现这一点。我了解如何创建与API的连接,但不知道如何为该方法编写请求主体以及在何处编写请求主体。我想知道如何指定新存储库的名称。我实际上很笨拙,不知道一般如何使用REST API。
我正在将Visual Studio与.NET Core 3.0一起使用,并计划将其与React.js一起使用
到目前为止,这是我正在使用的代码,我不知道从这里可以去哪里:
public class AzureDevOps {
public static async void GetRepositories()
{
try
{
var personalaccesstoken = "PAT_FROM_WEBSITE";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
using (HttpResponseMessage response = await client.GetAsync(
"https://dev.azure.com/{organization}/_apis/git/repositories?api-version=5.1"))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
我希望在此问题上进行任何澄清,并提供一些有关如何使用REST API的示例。提前致谢!
您应该使用POST
方法来创建存储库。在此处检查API:
该代码应如下所示:
var PAT = "xxxxx";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", PAT))));
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://dev.azure.com/{organization}/{project}/_apis/git/repositories?api-version=5.1");
requestMessage.Content = new StringContent("{\"name\": \"RepositoryName\",\"project\": {\"id\": \"xxxxxxx\"}}", Encoding.UTF8, "application/json");
using (HttpResponseMessage response = client.SendAsync(requestMessage).Result)
{
response.EnsureSuccessStatusCode();
}
}
更新:
var PAT = "xxxxx";
var body = new
{
name = "RepositoryName",
project = new
{
id = "xxxxxxx"
}
};
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", PAT))));
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://dev.azure.com/{organization}/{project}/_apis/git/repositories?api-version=5.1");
requestMessage.Content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
using (HttpResponseMessage response = client.SendAsync(requestMessage).Result)
{
response.EnsureSuccessStatusCode();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句