在 .NET 中開始使用轉送混合式連線 HTTP 要求

在本快速入門中,您會建立使用 HTTP 通訊協定來傳送和接收訊息的 .NET 傳送者和接收者應用程式。 應用程式使用 Azure 轉送的混合式 連線 功能。 若要瞭解 Azure 轉寄一般,請參閱 Azure 轉寄

在本快速入門中,您會採取下列步驟:

  1. 使用 Azure 入口網站 建立轉寄命名空間。
  2. 使用 Azure 入口網站,在該命名空間中建立混合式連線。
  3. 撰寫伺服器(接聽程式)控制台應用程式以接收訊息。
  4. 撰寫用戶端 (sender) 主控台應用程式以傳送訊息。
  5. 執行應用程式。

必要條件

若要完成本教學課程,您需要下列必要條件:

  • Visual Studio 2019 或更新版本。 本教學課程中的範例使用Visual Studio 2022。
  • Azure 訂用帳戶。 如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶

建立命名空間

  1. 登入 Azure 入口網站

  2. 選取左側功能表上的 [所有服務]。 依序選取 [整合]、搜尋 [轉寄]、將滑鼠移至 [轉寄] 上方,然後選取 [建立]。

    顯示選取 [轉寄 -> 建立] 按鈕的螢幕快照。

  3. 在 [ 建立命名空間] 頁面上,遵循下列步驟:

    1. 選擇要在其中建立命名空間的 Azure 訂用帳戶。

    2. 針對 [ 資源群組],選擇要放置命名空間的現有資源群組,或建立新的資源群組。

    3. 輸入轉寄命名空間的名稱。

    4. 選取您的命名空間應該裝載所在的區域。

    5. 選取頁面底部的 [檢閱 + 建立] 。

      顯示 [建立命名空間] 頁面的螢幕快照。

    6. 在 [檢閱 + 建立] 頁面上,選取 [建立]

    7. 幾分鐘后,您會看到 命名空間的 [轉寄 ] 頁面。

      顯示轉接命名空間首頁的螢幕快照。

取得管理認證

  1. 在 [ 轉寄 ] 頁面上,選取 左側功能表上的 [共用存取原則 ]。 `

  2. 在 [共用存取原則] 頁面上,選取 [RootManageSharedAccessKey]

  3. 在 [SAS 原則:RootManageSharedAccessKey] 下,選取 [主要 連線 ion 字串] 旁的 [複製] 按鈕。 此動作會將 連接字串 複製到剪貼簿以供稍後使用。 將此值貼到記事本或一些其他暫存位置。

  4. 重複上述步驟,將 [主要密鑰] 的值複製並貼到暫存位置,以供日後使用。

    顯示轉接命名空間之連線資訊的螢幕快照。

建立混合式連線

在命名空間的 [ 轉送 ] 頁面上,遵循下列步驟來建立混合式連線。

  1. 在左側功能表上的 [實體] 下,選取 [混合式 連線],然後選取 [+ 混合式 連線]。

    顯示混合式 連線 頁面的螢幕快照。

  2. 在 [建立混合式 連線 ion] 頁面上,輸入混合式連線的名稱,然後選取 [建立]。

    顯示 [建立混合式 連線] 頁面的螢幕快照。

建立伺服器應用程式 (接聽程式)

在 Visual Studio 中,撰寫 C# 控制台應用程式以接聽和接收來自轉播的訊息。

建立主控台應用程式

在 Visual Studio 中,建立新的 控制台應用程式 (.NET Framework) 專案。

新增轉寄 NuGet 套件

  1. 以滑鼠右鍵按下新建立的項目,然後選取 [ 管理 NuGet 套件]。
  2. 選取 [ 瀏覽],然後搜尋 Microsoft.Azure.Relay。 在搜尋結果中,選取 [Microsoft Azure 轉寄]。
  3. 選取 [ 安裝 ] 以完成安裝。 關閉對話方塊。

撰寫程式代碼以接收訊息

  1. 在Program.cs檔案頂端,以下列using語句取代現有的 using 語句:

    using System;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.Relay;
    using System.Net;
    
  2. 將常數新增至 Program 類別,以取得混合式連線詳細數據。 將方括弧中的佔位元取代為您在建立混合式連線時取得的值。 請務必使用完整命名空間名稱。

    // replace {RelayNamespace} with the name of your namespace
    private const string RelayNamespace = "{RelayNamespace}.servicebus.windows.net";
    
    // replace {HybridConnectionName} with the name of your hybrid connection
    private const string ConnectionName = "{HybridConnectionName}";
    
    // replace {SAKKeyName} with the name of your Shared Access Policies key, which is RootManageSharedAccessKey by default
    private const string KeyName = "{SASKeyName}";
    
    // replace {SASKey} with the primary key of the namespace you saved earlier
    private const string Key = "{SASKey}";
    
  3. RunAsync 方法新增至 Program 類別:

    private static async Task RunAsync()
    {
        var cts = new CancellationTokenSource();
    
        var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
        var listener = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);
    
        // Subscribe to the status events.
        listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
        listener.Offline += (o, e) => { Console.WriteLine("Offline"); };
        listener.Online += (o, e) => { Console.WriteLine("Online"); };
    
        // Provide an HTTP request handler
        listener.RequestHandler = (context) =>
        {
            // Do something with context.Request.Url, HttpMethod, Headers, InputStream...
            context.Response.StatusCode = HttpStatusCode.OK;
            context.Response.StatusDescription = "OK, This is pretty neat";
            using (var sw = new StreamWriter(context.Response.OutputStream))
            {
                sw.WriteLine("hello!");
            }
    
            // The context MUST be closed here
            context.Response.Close();
        };
    
        // Opening the listener establishes the control channel to
        // the Azure Relay service. The control channel is continuously 
        // maintained, and is reestablished when connectivity is disrupted.
        await listener.OpenAsync();
        Console.WriteLine("Server listening");
    
        // Start a new thread that will continuously read the console.
        await Console.In.ReadLineAsync();
    
        // Close the listener after you exit the processing loop.
        await listener.CloseAsync();
    }
    
  4. 將下列程式代碼列新增至 Main 類別中的 Program 方法:

    RunAsync().GetAwaiter().GetResult();
    

    已完成的Program.cs檔案看起來應該像這樣:

    namespace Server
    {
        using System;
        using System.IO;
        using System.Threading;
        using System.Threading.Tasks;
        using Microsoft.Azure.Relay;
        using System.Net;
    
        public class Program
        {
            private const string RelayNamespace = "{RelayNamespace}.servicebus.windows.net";
            private const string ConnectionName = "{HybridConnectionName}";
            private const string KeyName = "{SASKeyName}";
            private const string Key = "{SASKey}";
    
            public static void Main(string[] args)
            {
                RunAsync().GetAwaiter().GetResult();
            }
    
            private static async Task RunAsync()
            {
                var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
                var listener = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);
    
                // Subscribe to the status events.
                listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
                listener.Offline += (o, e) => { Console.WriteLine("Offline"); };
                listener.Online += (o, e) => { Console.WriteLine("Online"); };
    
                // Provide an HTTP request handler
                listener.RequestHandler = (context) =>
                {
                    // Do something with context.Request.Url, HttpMethod, Headers, InputStream...
                    context.Response.StatusCode = HttpStatusCode.OK;
                    context.Response.StatusDescription = "OK";
                    using (var sw = new StreamWriter(context.Response.OutputStream))
                    {
                        sw.WriteLine("hello!");
                    }
    
                    // The context MUST be closed here
                    context.Response.Close();
                };
    
                // Opening the listener establishes the control channel to
                // the Azure Relay service. The control channel is continuously 
                // maintained, and is reestablished when connectivity is disrupted.
                await listener.OpenAsync();
                Console.WriteLine("Server listening");
    
                // Start a new thread that will continuously read the console.
                await Console.In.ReadLineAsync();
    
                // Close the listener after you exit the processing loop.
                await listener.CloseAsync();
            }
        }
    }
    

建立用戶端應用程式 (寄件者)

在 Visual Studio 中,撰寫 C# 控制台應用程式以將訊息傳送至轉送。

建立主控台應用程式

如果您在建立轉送時停用 [需要用戶端授權] 選項,您可以使用任何瀏覽器將要求傳送至混合式 連線 IONS URL。 若要存取受保護的端點,您必須在標頭中 ServiceBusAuthorization 建立並傳遞令牌,如下所示。

在 Visual Studio 中,建立新的 控制台應用程式 (.NET Framework) 專案。

新增轉寄 NuGet 套件

  1. 以滑鼠右鍵按下新建立的項目,然後選取 [ 管理 NuGet 套件]。
  2. 選取 [ 包含發行前版本 ] 選項。
  3. 選取 [ 瀏覽],然後搜尋 Microsoft.Azure.Relay。 在搜尋結果中,選取 [Microsoft Azure 轉寄]。
  4. 選取 [ 安裝 ] 以完成安裝。 關閉對話方塊。

撰寫程式代碼以傳送要求

  1. 在Program.cs檔案頂端,以下列using語句取代現有的 using 語句:

    using System;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Net.Http;
    using Microsoft.Azure.Relay;
    
  2. 將常數新增至 Program 類別,以取得混合式連線詳細數據。 將方括弧中的佔位元取代為您在建立混合式連線時取得的值。 請務必使用完整命名空間名稱。

    // replace {RelayNamespace} with the name of your namespace
    private const string RelayNamespace = "{RelayNamespace}.servicebus.windows.net";
    
    // replace {HybridConnectionName} with the name of your hybrid connection
    private const string ConnectionName = "{HybridConnectionName}";
    
    // replace {SAKKeyName} with the name of your Shared Access Policies key, which is RootManageSharedAccessKey by default
    private const string KeyName = "{SASKeyName}";
    
    // replace {SASKey} with the primary key of the namespace you saved earlier
    private const string Key = "{SASKey}";
    
  3. 將下列方法新增至 Program班級:

    private static async Task RunAsync()
    {
        var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(
                KeyName, Key);
        var uri = new Uri(string.Format("https://{0}/{1}", RelayNamespace, ConnectionName));
        var token = (await tokenProvider.GetTokenAsync(uri.AbsoluteUri, TimeSpan.FromHours(1))).TokenString;
        var client = new HttpClient();
        var request = new HttpRequestMessage()
        {
            RequestUri = uri,
            Method = HttpMethod.Get,
        };
        request.Headers.Add("ServiceBusAuthorization", token);
        var response = await client.SendAsync(request);
        Console.WriteLine(await response.Content.ReadAsStringAsync());        Console.ReadLine();
    }
    
  4. 將下列程式代碼行新增至 Main 類別中的 Program 方法。

    RunAsync().GetAwaiter().GetResult();
    

    Program.cs看起來應該像這樣:

    using System;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Net.Http;
    using Microsoft.Azure.Relay;
    
    namespace Client
    {
        class Program
        {
            private const string RelayNamespace = "{RelayNamespace}.servicebus.windows.net";
            private const string ConnectionName = "{HybridConnectionName}";
            private const string KeyName = "{SASKeyName}";
            private const string Key = "{SASKey}";
    
            static void Main(string[] args)
            {
                RunAsync().GetAwaiter().GetResult();
            }
    
            private static async Task RunAsync()
            {
               var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(
                KeyName, Key);
                var uri = new Uri(string.Format("https://{0}/{1}", RelayNamespace, ConnectionName));
                var token = (await tokenProvider.GetTokenAsync(uri.AbsoluteUri, TimeSpan.FromHours(1))).TokenString;
                var client = new HttpClient();
                var request = new HttpRequestMessage()
                {
                    RequestUri = uri,
                    Method = HttpMethod.Get,
                };
                request.Headers.Add("ServiceBusAuthorization", token);
                var response = await client.SendAsync(request);
                Console.WriteLine(await response.Content.ReadAsStringAsync());
            }
        }
    }
    

執行應用程式

  1. 執行伺服器應用程式。 您會在主控台視窗中看到下列文字:

    Online
    Server listening
    
  2. 執行用戶端應用程式。 您會在客戶端視窗中看到 hello! 。 用戶端將 HTTP 要求傳送至伺服器,並使用 回應 hello!伺服器。

  3. 現在,若要關閉主控台視窗,請在兩個控制台視窗中按 ENTER

恭喜您,您已建立完整的混合式 連線 ions 應用程式!

下一步

在本快速入門中,您已建立使用 HTTP 來傳送和接收訊息的 .NET 用戶端和伺服器應用程式。 Azure 轉送的混合式 連線 功能也支援使用 WebSocket 來傳送和接收訊息。 若要瞭解如何搭配 Azure 轉送混合式 連線 使用 WebSocket,請參閱 WebSockets 快速入門

在本快速入門中,您已使用 .NET Framework 來建立用戶端和伺服器應用程式。 若要瞭解如何使用 Node.js 撰寫用戶端和伺服器應用程式,請參閱 Node.js WebSockets 快速入門Node.js HTTP 快速入門