Share via


適用於 Azure DevOps 的 REST API 範例

Azure DevOps Services | Azure DevOps Server 2022 - Azure DevOps Server 2019

本文中的大部分範例都會使用個人存取令牌(PAT)。 PAT 是驗證的精簡範例。 還有其他許多可用的驗證機制,包括 Microsoft 驗證連結庫、OAuth 和會話令牌。 如需量測最適合您案例的詳細資訊,請參閱 驗證指引

如需詳細資訊,請參閱 Azure DevOps Services REST API 參考開始使用 REST API

個人存取權杖

當您使用 REST API 或 .NET 連結庫時,請使用 Azure DevOps 進行驗證。

開始使用這些範例並 建立 PAT

提示

PAT 就像密碼。 讓他們保密。 建立 PAT 之後,請務必將它們儲存在安全的位置。

若要透過 HTTP 標頭提供 PAT,請先將它轉換成 Base64 字串。 下列範例示範如何使用 C# 轉換成 Base64。 您可以使用下列格式提供產生的字串做為 HTTP 標頭:

Authorization: Basic BASE64USERNAME:PATSTRING

REST API

請參閱下列範例,以透過 REST API 取得組織的項目清單。

using System.Net.Http;
using System.Net.Http.Headers;

...

//encode your personal access token                   
string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalAccessToken)));

ListOfProjectsResponse.Projects viewModel = null;

//use the httpclient
using (var client = new HttpClient())
{
    client.BaseAddress = new Uri($"https://dev.azure.com/{OrgName}/");  //url of your organization
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials); 

    //connect to the REST endpoint            
    HttpResponseMessage response = client.GetAsync("_apis/projects?stateFilter=All&api-version=1.0").Result;
          
    //check to see if we have a successful response
    if (response.IsSuccessStatusCode)
    {
        //set the viewmodel from the content in the response
        viewModel = response.Content.ReadAsAsync<ListOfProjectsResponse.Projects>().Result;
                
        //var value = response.Content.ReadAsStringAsync().Result;
    }   
}

.NET 用戶端連結庫

在這裡,我們使用兩個 .NET 用戶端連結庫。 請務必參考 .NET 專案中的下列 .NET 用戶端連結庫。

請參閱下列範例,以透過 .NET 用戶端連結庫取得組織的項目清單。

using Microsoft.TeamFoundation.Core.WebApi;
using Microsoft.VisualStudio.Services.Common;

...

//create uri and VssBasicCredential variables
Uri uri = new Uri(url);
VssBasicCredential credentials = new VssBasicCredential("", personalAccessToken);

using (ProjectHttpClient projectHttpClient = new ProjectHttpClient(uri, credentials))
{
    IEnumerable<TeamProjectReference> projects = projectHttpClient.GetProjects().Result;                    
}

常見問題集

問:我可以在哪裡取得程式碼範例的原始程式碼?

答:請參閱 https://github.com/Microsoft/vsts-restapi-samplecode

問:哪裡可以找到 .NET 連結庫的詳細資訊?

答:請參閱 客戶端連結庫的概觀。