開始使用適用於 .NET 的 Azure CDN 程式庫

重要

Azure CDN Standard from Microsoft (classic) 將於 2027 年 9 月 30 日淘汰。 為了避免任何服務中斷,請務必在 2027 年 9 月 30 日之前,移轉您的 Azure CDN Standard from Microsoft (classic) 設定檔至 Azure Front Door Standard 或 Premium 層。 如需詳細資訊,請參閱 Azure CDN Standard from Microsoft (classic) 淘汰

您可以使用 適用於 .NET 的 Azure CDN 程式庫 ,自動建立和管理 CDN 設定檔與端點。 本教學課程會逐步建立簡單的 .NET 主控台應用程式,示範數個可用的作業。 本教學課程並非旨在詳細說明適用於 .NET 的 Azure CDN 程式庫的所有層面。

您需要 Visual Studio 2015,才能完成本教學課程。 Visual Studio Community 2015 可供免費下載。

提示

您可以在 MSDN 上下載 本教學課程中完成的專案

必要條件

在撰寫 CDN 管理程式碼之前,您必須做一些準備工作,讓程式碼與 Azure Resource Manager 進行互動。 若要執行這項準備作業,您必須:

  • 建立資源群組,以包含本教學課程中建立的 CDN 設定檔
  • 設定 Microsoft Entra ID,針對應用程式提供驗證
  • 將權限套用到資源群組,以便只有來自您 Microsoft Entra 租用戶的授權使用者可以與 CDN 設定檔進行互動

建立資源群組

  1. 登入 Azure 入口網站

  2. 按一下 [建立資源]

  3. 搜尋 [資源群組],然後在 [資源群組] 窗格中,按一下 [建立]

    建立新的資源群組

  4. 將您的資源群組命名為 CdnConsoleTutorial 。 選取您的訂用帳戶,並選擇離您最近的位置。 您可以視需要按一下 [釘選到儀表板] 核取方塊,將資源群組釘選到入口網站的儀表板上。 釘選可方便日後尋找。 進行選擇之後,按一下 [建立]

    資源群組對話方塊的螢幕擷取畫面。

  5. 建立資源群組之後,如果您未將它釘選到儀表板,可以依序按一下 [瀏覽] 和 [資源群組] 來尋找。 如需開啟,請按一下資源群組。 請記下您的訂用帳戶 ID。 我們稍後將會用到此資訊。

    CDN 主控台教學課程區段的螢幕擷取畫面。

建立 Microsoft Entra 應用程式,然後套用權限

有兩種方式可以使用 Microsoft Entra ID 來進行應用程式驗證:個別使用者或服務主體。 服務主體類似於 Windows 中的服務帳戶。 我們並未授與特定使用者權限來與 CDN 設定檔互動,而是改為將權限授與服務主體。 服務主體通常用於自動化的非互動式處理程序。 雖然本教學課程是撰寫互動式主控台應用程式,但我們將著重在服務主體處理方法。

建立服務主體包含數個步驟,其中包括建立 Microsoft Entra 應用程式。 若要建立它,我們將遵循此教學課程

重要

請務必遵循教學課程連結中的所有步驟。 您必須如所述方式確實完成,這點「很重要」。 請務必記下您的租用戶識別碼租用戶網域名稱 (除非您指定了自訂網域,否則通常是 .onmicrosoft.com 網域)、用戶端識別碼用戶端驗證金鑰,因為我們稍後需要用到這項資訊。 務必謹慎地保護您的用戶端識別碼用戶端驗證金鑰,因為任何人都可以使用這些認證,以服務主體形式來執行作業。

當您要進入名為設定多租用戶應用程式的步驟時,選取 [否]

當您要進入將應用程式指派給角色步驟時,請使用稍早建立的資源群組 CdnConsoleTutorial,但指派 [CDN 設定檔參與者] 角色,而不是 [讀者] 角色。 當您將應用程式指派給資源群組中的 CDN 設定檔參與者 角色之後,請返回本教學課程。

一旦您建立服務主體並指派 CDN 設定檔參與者角色之後,資源群組的 [使用者] 刀鋒視窗看起來應該如下列映像所示。

[使用者] 刀鋒視窗

互動式使用者驗證

如果比起服務主體,您比較需要使用互動式個別使用者驗證,則此程序與服務主體的程序很類似。 事實上,您必須遵循相同的程序,但要進行些微變更。

重要

如果您選擇使用個別使用者驗證,而不是服務主體,只需遵循以下這些步驟。

  1. 當您建立應用程式,而不是 Web 應用程式時,請選擇 [原生應用程式]

    原生應用程式

  2. 在下一個頁面上,系統將提示您輸入重新導向 URI。 URI 不會進行驗證,但請記住您的輸入。 您稍後將會用到此資訊。

  3. 不需要 用戶端驗證金鑰

  4. 我們不會將服務主體指派給 CDN 設定檔參與者 角色,而是會指派個別使用者或群組。 在此範例中,您可以看到我已將「CDN 示範使用者」 指派給 CDN 設定檔參與者 角色。

    個別使用者存取

建立專案並新增 NuGet 封裝

現在,我們已為 CDN 設定檔建立資源群組,並為 Microsoft Entra 應用程式授與權限來管理該群組內的 CDN 設定檔和端點,我們可以開始建立應用程式。

重要

Microsoft.IdentityModel.Clients.ActiveDirectory NuGet 套件和 Azure AD 驗證程式庫 (ADAL) 已被取代。 自 2020 年 6 月 30 日起,未新增任何新功能。 強烈建議您升級。 如需詳細資訊,請參閱移轉指南

從 Visual Studio 2015 中,依序選取 [檔案]、[新增] 和 [專案...],以開啟 [新增專案] 對話方塊。 展開 [Visual C#],然後選取左側窗格中的 [Windows]。 選取中央窗格的 [主控台應用程式]。 為您的專案命名,然後選取 [確定]

新增專案

我們的專案將使用 NuGet 封裝內含的一些 Azure 程式庫。 讓我們將這些程式庫新增至專案。

  1. 依序選取 [工具] 功能表、[Nuget 封裝管理員] 及 [封裝管理員主控台]

    管理 Nuget 封裝

  2. 在 [封裝管理員主控台] 中,執行下列命令來安裝 Active Directory Authentication Library (ADAL)

    Install-Package Microsoft.Identity.Client

  3. 執行下列命令來安裝 Azure CDN 管理程式庫

    Install-Package Microsoft.Azure.Management.Cdn

指示詞、常數、主要方法和協助程式方法

讓我們開始撰寫程式的基本結構。

  1. 回到 [Program.cs] 索引標籤,使用下列命令取代頂端的 using 指示詞:

    using System;
    using System.Collections.Generic;
    using Microsoft.Azure.Management.Cdn;
    using Microsoft.Azure.Management.Cdn.Models;
    using Microsoft.Azure.Management.Resources;
    using Microsoft.Azure.Management.Resources.Models;
    using Microsoft.Identity.Client;
    using Microsoft.Rest;
    
  2. 我們必須定義一些我們的方法會用到的常數。 在 Program 類別中,但在 Main 方法之前,新增下列程式碼區塊。 務必視需要使用您自己的值來取代預留位置,包括 <角括號>

    //Tenant app constants
    private const string clientID = "<YOUR CLIENT ID>";
    private const string clientSecret = "<YOUR CLIENT AUTHENTICATION KEY>"; //Only for service principals
    private const string authority = "https://login.microsoftonline.com/<YOUR TENANT ID>/<YOUR TENANT DOMAIN NAME>";
    
    //Application constants
    private const string subscriptionId = "<YOUR SUBSCRIPTION ID>";
    private const string profileName = "CdnConsoleApp";
    private const string endpointName = "<A UNIQUE NAME FOR YOUR CDN ENDPOINT>";
    private const string resourceGroupName = "CdnConsoleTutorial";
    private const string resourceLocation = "<YOUR PREFERRED AZURE LOCATION, SUCH AS Central US>";
    
  3. 此外,也要在類別層級設定這兩個變數。 稍後會使用這些變數來判斷我們的設定檔和端點是否已經存在。

    static bool profileAlreadyExists = false;
    static bool endpointAlreadyExists = false;
    
  4. 取代 Main 方法,如下所示:

    static void Main(string[] args)
    {
        //Get a token
        AuthenticationResult authResult = GetAccessToken();
    
        // Create CDN client
        CdnManagementClient cdn = new CdnManagementClient(new TokenCredentials(authResult.AccessToken))
            { SubscriptionId = subscriptionId };
    
        ListProfilesAndEndpoints(cdn);
    
        // Create CDN Profile
        CreateCdnProfile(cdn);
    
        // Create CDN Endpoint
        CreateCdnEndpoint(cdn);
    
        Console.WriteLine();
    
        // Purge CDN Endpoint
        PromptPurgeCdnEndpoint(cdn);
    
        // Delete CDN Endpoint
        PromptDeleteCdnEndpoint(cdn);
    
        // Delete CDN Profile
        PromptDeleteCdnProfile(cdn);
    
        Console.WriteLine("Press Enter to end program.");
        Console.ReadLine();
    }
    
  5. 在我們的其他方法中有一些會透過「是/否」問題來提示使用者。 新增下列方法,以使其更加容易:

    private static bool PromptUser(string Question)
    {
        Console.Write(Question + " (Y/N): ");
        var response = Console.ReadKey();
        Console.WriteLine();
        if (response.Key == ConsoleKey.Y)
        {
            return true;
        }
        else if (response.Key == ConsoleKey.N)
        {
            return false;
        }
        else
        {
            // They pressed something other than Y or N.  Let's ask them again.
            return PromptUser(Question);
        }
    }
    

現在已撰寫了程式的基本結構,我們應該建立 Main 方法所呼叫的方法。

驗證

在可以使用 Azure CDN 管理庫之前,需要先驗證服務主體,並取得驗證權杖。 此方法會使用 Active Directory 驗證程式庫來擷取權杖。

private static AuthenticationResult GetAccessToken()
{
    AuthenticationContext authContext = new AuthenticationContext(authority);
    ClientCredential credential = new ClientCredential(clientID, clientSecret);
    AuthenticationResult authResult =
        authContext.AcquireTokenAsync("https://management.core.windows.net/", credential).Result;

    return authResult;
}

如果您使用個別使用者驗證,GetAccessToken 方法看起來就會稍有不同。

重要

如果您選擇使用個別使用者驗證,而不是服務主體,只需使用這個程式碼範例。

private static AuthenticationResult GetAccessToken()
{
    AuthenticationContext authContext = new AuthenticationContext(authority);
    AuthenticationResult authResult = authContext.AcquireTokenAsync("https://management.core.windows.net/",
        clientID, new Uri("http://<redirect URI>"), new PlatformParameters(PromptBehavior.RefreshSession)).Result;

    return authResult;
}

務必使用您在 Microsoft Entra ID 中註冊應用程式時所輸入的重新導向 URI 來取代 <redirect URI>

列出 CDN 設定檔和端點

現在我們已經準備好執行 CDN 作業。 方法的首要任務就是列出資源群組中的所有設定檔和端點,且如果找到與常數中所指定的設定檔和端點名稱相符的項目,請記下該項目以供後續使用,如此一來,我們就不用嘗試建立重複的項目。

private static void ListProfilesAndEndpoints(CdnManagementClient cdn)
{
    // List all the CDN profiles in this resource group
    var profileList = cdn.Profiles.ListByResourceGroup(resourceGroupName);
    foreach (Profile p in profileList)
    {
        Console.WriteLine("CDN profile {0}", p.Name);
        if (p.Name.Equals(profileName, StringComparison.OrdinalIgnoreCase))
        {
            // Hey, that's the name of the CDN profile we want to create!
            profileAlreadyExists = true;
        }

        //List all the CDN endpoints on this CDN profile
        Console.WriteLine("Endpoints:");
        var endpointList = cdn.Endpoints.ListByProfile(p.Name, resourceGroupName);
        foreach (Endpoint e in endpointList)
        {
            Console.WriteLine("-{0} ({1})", e.Name, e.HostName);
            if (e.Name.Equals(endpointName, StringComparison.OrdinalIgnoreCase))
            {
                // The unique endpoint name already exists.
                endpointAlreadyExists = true;
            }
        }
        Console.WriteLine();
    }
}

建立 CDN 設定檔和端點

接下來,我們會建立設定檔。

private static void CreateCdnProfile(CdnManagementClient cdn)
{
    if (profileAlreadyExists)
    {
        Console.WriteLine("Profile {0} already exists.", profileName);
    }
    else
    {
        Console.WriteLine("Creating profile {0}.", profileName);
        ProfileCreateParameters profileParms =
            new ProfileCreateParameters() { Location = resourceLocation, Sku = new Sku(SkuName.StandardVerizon) };
        cdn.Profiles.Create(profileName, profileParms, resourceGroupName);
    }
}

建立設定檔之後,我們將建立端點。

private static void CreateCdnEndpoint(CdnManagementClient cdn)
{
    if (endpointAlreadyExists)
    {
        Console.WriteLine("Profile {0} already exists.", profileName);
    }
    else
    {
        Console.WriteLine("Creating endpoint {0} on profile {1}.", endpointName, profileName);
        EndpointCreateParameters endpointParms =
            new EndpointCreateParameters()
            {
                Origins = new List<DeepCreatedOrigin>() { new DeepCreatedOrigin("Contoso", "www.contoso.com") },
                IsHttpAllowed = true,
                IsHttpsAllowed = true,
                Location = resourceLocation
            };
        cdn.Endpoints.Create(endpointName, endpointParms, profileName, resourceGroupName);
    }
}

注意

上述範例會為端點指派一個名為Contoso 的來源且主機名稱為 www.contoso.com。 您應該變更此項以指向您自己來源的主機名稱。

清除端點

假設端點已建立,我們可能想要在程式中執行的一個常見工作是清除此端點中的內容。

private static void PromptPurgeCdnEndpoint(CdnManagementClient cdn)
{
    if (PromptUser(String.Format("Purge CDN endpoint {0}?", endpointName)))
    {
        Console.WriteLine("Purging endpoint. Please wait...");
        cdn.Endpoints.PurgeContent(resourceGroupName, profileName, endpointName, new List<string>() { "/*" });
        Console.WriteLine("Done.");
        Console.WriteLine();
    }
}

注意

在上述範例中,字串 /* 代表我想要清除端點路徑根目錄中的所有項目。 這相當於在 Azure 入口網站的 [清除] 對話方塊中勾選 [全部清除]。 在 CreateCdnProfile 方法中,我已經使用程式碼 Sku = new Sku(SkuName.StandardVerizon) 來建立設定檔做為來自 Edgio 的 Azure CDN 設定檔,因此這將會成功。

刪除 CDN 設定檔和端點

最後一個方法會刪除我們的端點和設定檔。

private static void PromptDeleteCdnEndpoint(CdnManagementClient cdn)
{
    if(PromptUser(String.Format("Delete CDN endpoint {0} on profile {1}?", endpointName, profileName)))
    {
        Console.WriteLine("Deleting endpoint. Please wait...");
        cdn.Endpoints.DeleteIfExists(endpointName, profileName, resourceGroupName);
        Console.WriteLine("Done.");
        Console.WriteLine();
    }
}

private static void PromptDeleteCdnProfile(CdnManagementClient cdn)
{
    if(PromptUser(String.Format("Delete CDN profile {0}?", profileName)))
    {
        Console.WriteLine("Deleting profile. Please wait...");
        cdn.Profiles.DeleteIfExists(profileName, resourceGroupName);
        Console.WriteLine("Done.");
        Console.WriteLine();
    }
}

執行程式

我們現在可以按一下 Visual Studio 中的 [開始] 按鈕來編譯及執行程式。

程式正在執行中

當程式達到上述提示時,您應該能夠回到您在 Azure 入口網站中的資源群組,並看見設定檔已建立。

成功!

接著,可確認提示來執行程式的其餘部分。

正在完成程式

後續步驟

若要查看此逐步解說中已完成的專案,請 下載範例

若要尋找適用於 .NET 的 Azure CDN 管理程式庫的其他相關文件,請檢視 MSDN 上的參考

使用 PowerShell管理 CDN 資源。