C# Azure DevOps API 检索所有项目
C# Azure DevOps API retrieve all projects
我有以下内容。在 GetAllProjects 中发出请求后,它似乎没有等待。它等待响应,然后不等待读入响应内容。
注意:为 ReadAsAsync 使用 nuget 包(但是可以使用 json 对象反序列化)
public class Project
{
public string? Id { get; set; }
public string? Name { get; set; }
public string? Url { get; set; }
}
public class Main
{
public static void Main(string[] args)
{
AzureClient ac = new AzureClient();
var projects = ac.GetAllProjects();
}
}
public class AzureClient
{
private readonly HttpClient _client;
private const string PAT = "myToken";
private const string API_VERSION = "api-version=5.0";
public AzureClient()
{
_client = new HttpClient()
{
BaseAddress = new Uri("some uri"),
Timeout = TimeSpan.FromSeconds(30)
};
// added media type and passed in auth token to _client. client returns 200 on requests
}
public async Task<ICollection<Project>> GetAllProjects()
{
var response = await _client.GetAsync("_apis/projects?{API_VERSION }");
var projects = await response.Content.ReadAsAsync<dynamic>();
return projects.value.ToObject<ICollection<Project>>();
}
}
您在这里缺少等待
var projects = await ac.GetAllProjects();
您还需要将 Main 方法设为异步
我有以下内容。在 GetAllProjects 中发出请求后,它似乎没有等待。它等待响应,然后不等待读入响应内容。 注意:为 ReadAsAsync 使用 nuget 包(但是可以使用 json 对象反序列化)
public class Project
{
public string? Id { get; set; }
public string? Name { get; set; }
public string? Url { get; set; }
}
public class Main
{
public static void Main(string[] args)
{
AzureClient ac = new AzureClient();
var projects = ac.GetAllProjects();
}
}
public class AzureClient
{
private readonly HttpClient _client;
private const string PAT = "myToken";
private const string API_VERSION = "api-version=5.0";
public AzureClient()
{
_client = new HttpClient()
{
BaseAddress = new Uri("some uri"),
Timeout = TimeSpan.FromSeconds(30)
};
// added media type and passed in auth token to _client. client returns 200 on requests
}
public async Task<ICollection<Project>> GetAllProjects()
{
var response = await _client.GetAsync("_apis/projects?{API_VERSION }");
var projects = await response.Content.ReadAsAsync<dynamic>();
return projects.value.ToObject<ICollection<Project>>();
}
}
您在这里缺少等待
var projects = await ac.GetAllProjects();
您还需要将 Main 方法设为异步