共用方式為


適用於 Azure DevOps 的 SOAP 用戶端連結庫範例

Azure DevOps 服務 |Azure DevOps Server |Azure DevOps Server 2022

警告

舊版技術 - 建議使用新式替代方案

這些 SOAP 型用戶端是舊版技術,只能用於:

  • 維護無法現代化的現有應用程式
  • 需要SOAP特定功能的 .NET Framework 應用程式

針對新的開發,請使用提供下列功能的新 式 REST 型 .NET 用戶端連結庫

  • ✅ 更好的效能和可靠性
  • ✅ 支援 .NET Core、.NET 5+和 .NET Framework
  • ✅ 新式驗證方法 (受控識別、服務主體)
  • ✅ Async/await 模式和新式 C# 功能
  • ✅ 主動開發和支援

本文包含使用舊版 SOAP 用戶端與 Azure DevOps Server 和 Azure DevOps Services 整合的範例。 這些用戶端僅適用於 .NET Framework 版本,而且需要內部部署或舊版驗證方法。

先決條件與限制

Requirements:

  • .NET Framework 4.6.1 或更新版本
  • 舊版 NuGet 套件
  • 適用於 SOAP 用戶端支援的 Windows 環境

限制:

  • ❌ 不支援 .NET Core 或 .NET 5+
  • ❌ 有限的新式驗證選項
  • ❌ 無 async/await 模式
  • ❌ 相較於 REST 用戶端,效能降低
  • ❌ 未來的支援和更新有限

必要的 NuGet 套件:

移轉指引

步驟 1:評估您目前的使用量

  • 識別應用程式所使用的SOAP特定功能
  • 判斷是否提供對等的 REST API
  • 評估驗證需求

步驟 2:規劃移轉策略

  • 立即:更新驗證以使用 PAT 或Microsoft Entra 標識碼
  • 短期:移轉至以 REST 為基礎的用戶端,同時保留 .NET Framework
  • 長期:使用 REST 用戶端現代化至 .NET Core/.NET 5+

步驟 3:實作移轉

  • 從驗證更新開始。 請參閱下列範例。
  • 逐步將 SOAP 用戶端替換為 REST 等效方案
  • 在部署到生產環境之前徹底測試

如需詳細的移轉指引,請參閱 .NET 用戶端連結庫範例

舊版 SOAP 用戶端範例

基本 SOAP 用戶端使用方式

這很重要

此範例僅顯示參考的舊版模式。 使用 REST 型範例 進行新的開發。

using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.VisualStudio.Services.Common;
using System;
using System.Linq;

/// <summary>
/// Legacy SOAP client example - use REST clients for new development
/// Creates a work item query, runs it, and displays results
/// </summary>
public static class LegacySoapExample
{
    public static void ExecuteWorkItemQuery(string collectionUri, string teamProjectName, VssCredentials credentials)
    {
        try
        {
            // Create TfsTeamProjectCollection instance with credentials
            using (var tpc = new TfsTeamProjectCollection(new Uri(collectionUri), credentials))
            {
                // Authenticate the connection
                tpc.Authenticate();
                
                // Get the WorkItemStore service (SOAP-based)
                var workItemStore = tpc.GetService<WorkItemStore>();
                
                // Get the project context
                var workItemProject = workItemStore.Projects[teamProjectName];
                
                // Find 'My Queries' folder
                var myQueriesFolder = workItemProject.QueryHierarchy
                    .OfType<QueryFolder>()
                    .FirstOrDefault(qh => qh.IsPersonal);
                
                if (myQueriesFolder != null)
                {
                    const string queryName = "Legacy SOAP Sample";
                    
                    // Check if query already exists
                    var existingQuery = myQueriesFolder
                        .OfType<QueryDefinition>()
                        .FirstOrDefault(qi => qi.Name.Equals(queryName, StringComparison.OrdinalIgnoreCase));
                    
                    QueryDefinition queryDefinition;
                    if (existingQuery == null)
                    {
                        // Create new query with proper WIQL
                        queryDefinition = new QueryDefinition(
                            queryName,
                            @"SELECT [System.Id], [System.WorkItemType], [System.Title], 
                                     [System.AssignedTo], [System.State], [System.Tags] 
                              FROM WorkItems 
                              WHERE [System.TeamProject] = @project 
                                AND [System.WorkItemType] = 'Bug' 
                                AND [System.State] = 'New'
                              ORDER BY [System.CreatedDate] DESC");
                        
                        myQueriesFolder.Add(queryDefinition);
                        workItemProject.QueryHierarchy.Save();
                    }
                    else
                    {
                        queryDefinition = existingQuery;
                    }
                    
                    // Execute the query
                    var workItems = workItemStore.Query(queryDefinition.QueryText);
                    
                    Console.WriteLine($"Found {workItems.Count} work items:");
                    foreach (WorkItem workItem in workItems)
                    {
                        var title = workItem.Fields["System.Title"].Value;
                        var state = workItem.Fields["System.State"].Value;
                        Console.WriteLine($"#{workItem.Id}: {title} [{state}]");
                    }
                    
                    if (workItems.Count == 0)
                    {
                        Console.WriteLine("No work items found matching the query criteria.");
                    }
                }
                else
                {
                    Console.WriteLine("'My Queries' folder not found.");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error executing SOAP query: {ex.Message}");
            throw;
        }
    }
}

舊版驗證方法

警告

這些驗證方法具有安全性限制。 盡可能移轉至 新式驗證

/// <summary>
/// Authenticate SOAP client using Personal Access Token
/// Most secure option for legacy SOAP clients
/// </summary>
public static void AuthenticateWithPAT(string collectionUri, string personalAccessToken)
{
    try
    {
        var credentials = new VssBasicCredential(string.Empty, personalAccessToken);
        
        using (var tpc = new TfsTeamProjectCollection(new Uri(collectionUri), credentials))
        {
            tpc.Authenticate();
            Console.WriteLine($"Successfully authenticated to: {tpc.DisplayName}");
            Console.WriteLine($"Instance ID: {tpc.InstanceId}");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"PAT authentication failed: {ex.Message}");
        throw;
    }
}

Microsoft Entra 驗證 (有限支援)

/// <summary>
/// Microsoft Entra authentication for SOAP services
/// Limited to specific scenarios - prefer REST clients for modern auth
/// </summary>
public static void AuthenticateWithEntraID(string collectionUri)
{
    try
    {
        // Note: Limited authentication options compared to REST clients
        var credentials = new VssAadCredential();
        
        using (var tpc = new TfsTeamProjectCollection(new Uri(collectionUri), credentials))
        {
            tpc.Authenticate();
            Console.WriteLine($"Successfully authenticated with Microsoft Entra ID");
            Console.WriteLine($"Collection: {tpc.DisplayName}");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Microsoft Entra authentication failed: {ex.Message}");
        Console.WriteLine("Consider migrating to REST clients for better authentication support.");
        throw;
    }
}

互動式驗證(僅限.NET Framework)

/// <summary>
/// Interactive authentication with Visual Studio sign-in prompt
/// Only works in .NET Framework with UI context
/// </summary>
public static void AuthenticateInteractively(string collectionUri)
{
    try
    {
        var credentials = new VssClientCredentials();
        
        using (var tpc = new TfsTeamProjectCollection(new Uri(collectionUri), credentials))
        {
            tpc.Authenticate();
            Console.WriteLine($"Interactive authentication successful");
            Console.WriteLine($"Authenticated user: {tpc.AuthorizedIdentity.DisplayName}");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Interactive authentication failed: {ex.Message}");
        Console.WriteLine("Ensure application has UI context and user interaction is possible.");
        throw;
    }
}

使用者名稱/密碼驗證 (已淘汰)

謹慎

使用者名稱/密碼驗證已被取代且不安全。 請改用 PAT 或新式驗證方法。

/// <summary>
/// Username/password authentication - DEPRECATED AND INSECURE
/// Only use for legacy on-premises scenarios where no alternatives exist
/// </summary>
[Obsolete("Username/password authentication is deprecated. Use PATs or modern authentication.")]
public static void AuthenticateWithUsernamePassword(string collectionUri, string username, string password)
{
    try
    {
        var credentials = new VssAadCredential(username, password);
        
        using (var tpc = new TfsTeamProjectCollection(new Uri(collectionUri), credentials))
        {
            tpc.Authenticate();
            Console.WriteLine("Username/password authentication successful (DEPRECATED)");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Username/password authentication failed: {ex.Message}");
        Console.WriteLine("This method is deprecated. Please migrate to PATs or modern authentication.");
        throw;
    }
}

完成舊版範例

using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.VisualStudio.Services.Common;
using System;
using System.Configuration;

/// <summary>
/// Complete example showing legacy SOAP client usage
/// For reference only - use REST clients for new development
/// </summary>
class LegacySoapProgram
{
    static void Main(string[] args)
    {
        try
        {
            // Get configuration (prefer environment variables or secure config)
            var collectionUri = ConfigurationManager.AppSettings["CollectionUri"];
            var projectName = ConfigurationManager.AppSettings["ProjectName"];
            var personalAccessToken = ConfigurationManager.AppSettings["PAT"]; // Store securely
            
            if (string.IsNullOrEmpty(collectionUri) || string.IsNullOrEmpty(projectName))
            {
                Console.WriteLine("Please configure CollectionUri and ProjectName in app.config");
                return;
            }
            
            Console.WriteLine("=== Legacy SOAP Client Example ===");
            Console.WriteLine("WARNING: This uses deprecated SOAP clients.");
            Console.WriteLine("Consider migrating to REST clients for better performance and support.");
            Console.WriteLine();
            
            VssCredentials credentials;
            
            if (!string.IsNullOrEmpty(personalAccessToken))
            {
                // Recommended: Use PAT authentication
                credentials = new VssBasicCredential(string.Empty, personalAccessToken);
                Console.WriteLine("Using Personal Access Token authentication");
            }
            else
            {
                // Fallback: Interactive authentication (requires UI)
                credentials = new VssClientCredentials();
                Console.WriteLine("Using interactive authentication");
            }
            
            // Execute the legacy SOAP example
            LegacySoapExample.ExecuteWorkItemQuery(collectionUri, projectName, credentials);
            
            Console.WriteLine();
            Console.WriteLine("Example completed successfully.");
            Console.WriteLine("For new development, see: https://docs.microsoft.com/azure/devops/integrate/concepts/dotnet-client-libraries");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
            Console.WriteLine();
            Console.WriteLine("Migration recommendations:");
            Console.WriteLine("1. Update to REST-based client libraries");
            Console.WriteLine("2. Use modern authentication (managed identities, service principals)");
            Console.WriteLine("3. Migrate to .NET Core/.NET 5+ for better performance");
            
            Environment.Exit(1);
        }
        
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
}

移轉至新式用戶端

並列比較

舊版 SOAP 方法:

// ❌ Legacy SOAP pattern
using (var tpc = new TfsTeamProjectCollection(uri, credentials))
{
    var workItemStore = tpc.GetService<WorkItemStore>();
    var workItems = workItemStore.Query("SELECT * FROM WorkItems");
    // Synchronous, blocking operations
}

新式 REST 方法:

// ✅ Modern REST pattern
using var connection = new VssConnection(uri, credentials);
var witClient = connection.GetClient<WorkItemTrackingHttpClient>();
var workItems = await witClient.QueryByWiqlAsync(new Wiql { Query = "SELECT * FROM WorkItems" });
// Asynchronous, non-blocking operations

主要差異

特徵 / 功能 舊版 SOAP 新式 REST
平台支援 僅限 .NET Framework .NET Framework、.NET Core、.NET 5+
效能 速度較慢,同步 更快速及非同步
驗證 有限選項 完整的新式驗證支援
API 涵蓋範圍 僅限舊版 API 完成 REST API 涵蓋範圍
未來的支援 僅限維護 主動開發
程序代碼模式 同步封鎖 非同步/await 模式

針對舊版客戶端進行疑難解答

常見問題和解決方案

驗證失敗:

  • 確定 PAT 有適當的範圍
  • 確認組織 URL 格式(包括內部部署的集合)
  • 檢查SOAP端點的防火牆和 Proxy 設定

效能問題:

  • SOAP 用戶端本質上比 REST 慢
  • 盡可能考慮批次作業
  • 遷移至 REST 用戶端以提升效能

平臺相容性:

  • SOAP 用戶端只能在 .NET Framework 上運作
  • 使用 REST 用戶端進行跨平台支援

尋求幫助

針對舊版 SOAP 用戶端問題:

  1. 查看 Azure DevOps 開發人員社群
  2. 檢視 移轉指引 以採用新式替代方案
  3. 考慮大型應用程式的專業移轉服務

移轉資源:

舊版文件:

這很重要

規劃移轉?新式 .NET 用戶端連結庫範例 開始,以查看目前的最佳做法和驗證選項。