.NET での Relay ハイブリッド接続 HTTP 要求の概要

このクイック スタートでは、HTTP プロトコルを使用してメッセージを送受信する .NET のセンダー アプリケーションとレシーバー アプリケーションを作成します。 これらのアプリケーションには、Azure Relay のハイブリッド接続機能が使用されます。 Azure Relay 全般については、Azure Relay に関するページを参照してください。

このクイック スタートでは、以下の手順を実行します。

  1. Azure Portal を使用した Relay 名前空間の作成
  2. Azure Portal を使用した、その名前空間内のハイブリッド接続の作成
  3. メッセージを受信するサーバー (リスナー) コンソール アプリケーションの作成
  4. メッセージを送信するクライアント (送信側) コンソール アプリケーションの作成
  5. アプリケーションの実行

前提条件

このチュートリアルを完了するには、次の前提条件を用意しておく必要があります。

  • Visual Studio 2019 以降。 このチュートリアルの例では、Visual Studio 2022 を使用します。
  • Azure サブスクリプション。 お持ちでない場合は、開始する前に無料アカウントを作成してください。

名前空間の作成

  1. Azure portal にサインインします。

  2. 左側のメニューから、 [すべてのサービス] を選択します。 [統合] を選択し、[リレー] を検索し、[リレー] の上にマウス ポインターを移動して、[作成] を選択します。

    [リレー] -> [作成] ボタンの選択を示すスクリーンショット。

  3. [名前空間の作成] ページで、これらの手順を実行します。

    1. 名前空間を作成する Azure サブスクリプションを選択します。

    2. [リソース グループ] で、名前空間を追加する既存のリソース グループを選択するか、新しいリソース グループを作成します。

    3. リレー名前空間の名前を入力します。

    4. 名前空間をホストするリージョンを選択します。

    5. ページ下部にある [確認と作成] を選択します。

      [名前空間の作成] ページを示すスクリーンショット。

    6. [確認および作成] ページで、 [作成] を選択します。

    7. 数分後に、名前空間の [リレー] ページを確認します。

      リレー名前空間のホーム ページを示すスクリーンショット。

管理資格情報を取得する

  1. [リレー] ページで、左側のメニューの [共有アクセス ポリシー] を選択します。 `

  2. [共有アクセス ポリシー] ページで、 [RootManageSharedAccessKey] を選択します。

  3. [SAS ポリシー:RootManageSharedAccessKey] の下で、 [プライマリ接続文字列] の横の [コピー] ボタンを選択します。 これで、後で使用できるように接続文字列がクリップボードにコピーされます。 この値をメモ帳などに一時的に貼り付けます。

  4. 前の手順を繰り返し、 [主キー] の値をコピーして、後で使用するために一時的な場所に貼り付けます。

    リレー名前空間の接続情報を示すスクリーンショット。

ハイブリッド接続の追加

名前空間の [リレー] ページで、次の手順に従ってハイブリッド接続を作成します。

  1. 左側のメニューの [エンティティ] の下で、[ハイブリッド接続] を選択し、[+ ハイブリッド接続] を選択します。

    [ハイブリッド接続] ページを示すスクリーンショット。

  2. [ハイブリッド接続の作成] ページで、ハイブリッド接続の名前を入力し、[作成] を選択します。

    [ハイブリッド接続の作成] ページを示すスクリーンショット。

サーバー アプリケーション (リスナー) の作成

Visual Studio で C# コンソール アプリケーションを作成して、Relay からのメッセージをリッスンおよび受信します。

コンソール アプリケーションを作成する

Visual Studio で、新しいコンソール アプリ (.NET Framework) プロジェクトを作成します。

Relay NuGet パッケージを追加する

  1. 新しく作成したプロジェクトを右クリックしてから、[NuGet パッケージの管理] を選択します。
  2. [参照] を選択し、Microsoft.Azure.Relay を検索します。 検索結果から、"Microsoft Azure Relay" を選択します。
  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. Program クラスの Main メソッドに次のコード行を追加します。

    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# コンソール アプリケーションを作成して、Relay にメッセージを送信します。

コンソール アプリケーションを作成する

リレーの作成時に [クライアント認証が必要] オプションを無効にしていた場合には、ブラウザーを問わずハイブリッド接続 URL に要求を送信できます。 保護されているエンドポイントにアクセスするには、ここに示したように ServiceBusAuthorization ヘッダーでトークンを作成して渡す必要があります。

Visual Studio で、新しいコンソール アプリ (.NET Framework) プロジェクトを作成します。

Relay NuGet パッケージを追加する

  1. 新しく作成したプロジェクトを右クリックしてから、[NuGet パッケージの管理] を選択します。
  2. [プレリリースを含める] オプションを選択します。
  3. [参照] を選択し、Microsoft.Azure.Relay を検索します。 検索結果から、"Microsoft Azure Relay" を選択します。
  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. Program クラスの Main メソッドに次のコード行を追加します。

    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 キーを押します。

これで、完全なハイブリッド接続のアプリケーションが作成されました。

次のステップ

このクイック スタートでは、HTTP を使用してメッセージを送受信する .NET のクライアント アプリケーションとサーバー アプリケーションを作成しました。 Azure Relay のハイブリッド接続機能は、WebSocket を使用したメッセージの送受信もサポートしています。 Azure Relay のハイブリッド接続で WebSocket を使用する方法については、WebSocket のクイック スタートを参照してください。

このクイック スタートでは、.NET Framework を使用してクライアント アプリケーションとサーバー アプリケーションを作成しました。 Node.js を使用してクライアント アプリケーションとサーバー アプリケーションを作成する方法については、Node.js WebSocket のクイック スタートまたは Node.js HTTP のクイック スタートを参照してください。