快速入門:使用 SignalR 服務建立聊天室Quickstart: Create a chat room by using SignalR Service

Azure SignalR 服務是可以協助開發人員使用即時功能輕鬆地建置 Web 應用程式的 Azure 服務。Azure SignalR Service is an Azure service that helps developers easily build web applications with real-time features. 此服務是以適用於 ASP.NET Core 2.0 的 SignalR (機器翻譯) 為基礎。This service is based on SignalR for ASP.NET Core 2.0.

本文會示範如何開始使用 Azure SignalR 服務。This article shows you how to get started with the Azure SignalR Service. 在此快速入門中,您將會使用 ASP.NET Core MVC Web 應用程式建立聊天應用程式。In this quickstart, you'll create a chat application by using an ASP.NET Core MVC web app. 此應用程式會與您的 Azure SignalR 服務資源連線,以提供即時的內容更新。This app will make a connection with your Azure SignalR Service resource to enable real-time content updates. 您將會於本機裝載 Web 應用程式,並與多個瀏覽器用戶端連線。You'll host the web application locally and connect with multiple browser clients. 每個用戶端都將能把內容更新推送至所有其他用戶端。Each client will be able to push content updates to all other clients.

您可以使用任何程式碼編輯器來完成本快速入門中的步驟。You can use any code editor to complete the steps in this quickstart. Windows、macOS 及 Linux 平台上都有提供的 Visual Studio Code (英文) 是一個選項。One option is Visual Studio Code, which is available on the Windows, macOS, and Linux platforms.

本教學課程的程式碼可於 AzureSignalR-samples GitHub 存放庫下載。The code for this tutorial is available for download in the AzureSignalR-samples GitHub repository. 您也可以依照建立 SignalR 服務指令碼中的說明,建立此快速入門中使用的 Azure 資源。Also, you can create the Azure resources used in this quickstart by following Create a SignalR Service script.

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin.

必要條件Prerequisites

建立 Azure SignalR 資源Create an Azure SignalR resource

  1. 若要建立 Azure SignalR Service 資源,請先登入 Azure 入口網站To create an Azure SignalR Service resource, first sign in to the Azure portal. 在頁面的左側,選取 [+ 建立資源] 。In the upper-left side of the page, select + Create a resource. 在 [搜尋 Marketplace] 文字方塊中,輸入 SignalR ServiceIn the Search the Marketplace text box, enter SignalR Service.

  2. 在結果中選取 [SignalR Service] ,然後選取 [建立] 。Select SignalR Service in the results, and select Create.

  3. 在新的 SignalR 設定頁面中,為新的 SignalR 資源新增下列設定:On the new SignalR settings page, add the following settings for your new SignalR resource:

    NameName 建議值Recommended value 說明Description
    資源名稱Resource name testsignalrtestsignalr 輸入要對 SignalR 資源使用的唯一資源名稱。Enter a unique resource name to use for the SignalR resource. 名稱必須是 1 到 63 個字元的字串,而且只能包含數字、字母和連字號 (-) 字元。The name must be a string of 1 to 63 characters and contain only numbers, letters, and the hyphen (-) character. 名稱的開頭或結尾不能是連字號字元,且連續的連字號字元無效。The name cannot start or end with the hyphen character, and consecutive hyphen characters are not valid.
    訂用帳戶Subscription 選擇您的訂用帳戶Choose your subscription 選取您要用來測試 SignalR 的 Azure 訂用帳戶。Select the Azure subscription that you want to use to test SignalR. 如果您的帳戶僅有一個訂用帳戶,則會自動加以選取,而且不會顯示 [訂用帳戶] 下拉式清單。If your account has only one subscription, it's automatically selected and the Subscription drop-down isn't displayed.
    資源群組Resource group 建立名為 SignalRTestResources 的新資源群組Create a resource group named SignalRTestResources 選取或建立 SignalR 資源的資源群組。Select or create a resource group for your SignalR resource. 此群組可用於組織多個資源,以便能夠藉由刪除資源群組來同時刪除多個資源。This group is useful for organizing multiple resources that you might want to delete at the same time by deleting the resource group. 如需詳細資訊,請參閱 使用資源群組來管理您的 Azure 資源For more information, see Using resource groups to manage your Azure resources.
    位置Location 美國東部 East US 使用 [位置] 來指定 SignalR 資源的裝載所在地理位置。Use Location to specify the geographic location in which your SignalR resource is hosted. 為獲得最佳效能,建議您在與應用程式其他元件相同的區域中建立資源。For the best performance, we recommend that you create the resource in the same region as other components of your application.
    定價層Pricing tier 免費Free 目前有 [免費] 和 [標準] 選項可供使用。Currently, Free and Standard options are available.
    釘選到儀表板Pin to dashboard 選取此方塊可將資源釘選到儀表板,因此很方便尋找。Select this box to have the resource pinned to your dashboard so it's easier to find.
  4. 選取 [建立] 。Select Create. 部署可能需要幾分鐘的時間才能完成。The deployment might take a few minutes to complete.

  5. 部署完成後,選取 [設定] 下方的 [金鑰] 。After the deployment is complete, select Keys under SETTINGS. 複製主索引鍵的連接字串。Copy your connection string for the primary key. 您稍後會將此字串用於設定應用程式,使其使用 Azure SignalR Service 資源。You'll use this string later to configure your app to use the Azure SignalR Service resource.

    連接字串的格式如下:The connection string will have the following form:

     Endpoint=<service_endpoint>;AccessKey=<access_key>;
    

建立 ASP.NET Core Web 應用程式Create an ASP.NET Core web app

在本節中,您會使用 .NET Core 命令列介面 (CLI) (英文) 來建立 ASP.NET Core MVC Web 應用程式專案。In this section, you use the .NET Core command-line interface (CLI) to create an ASP.NET Core MVC web app project. 使用 .NET Core CLI 而非 Visual Studio 的好處,在於 .NET Core CLI 可同時於 Windows、macOS 及 Linux 平台上取得。The advantage of using the .NET Core CLI over Visual Studio is that it's available across the Windows, macOS, and Linux platforms.

  1. 為您的專案建立資料夾。Create a folder for your project. 本快速入門會使用 E:\Testing\chattest 資料夾。This quickstart uses the E:\Testing\chattest folder.

  2. 在新的資料夾中,執行以下命令以建立專案:In the new folder, run the following command to create the project:

     dotnet new mvc
    

將祕密管理員新增至專案Add Secret Manager to the project

在本節中,您會將祕密管理員工具 (機器翻譯) 新增至您的專案。In this section, you'll add the Secret Manager tool to your project. 祕密管理員工具能儲存專案樹狀結構外開發工作的敏感性資料。The Secret Manager tool stores sensitive data for development work outside your project tree. 此作法能協助避免於原始程式碼內意外共用應用程式祕密。This approach helps prevent the accidental sharing of app secrets in source code.

  1. 開啟您的 .csproj 檔案。Open your .csproj file. 新增 DotNetCliToolReference 元素以包含 Microsoft.Extensions.SecretManager.ToolsAdd a DotNetCliToolReference element to include Microsoft.Extensions.SecretManager.Tools. 也新增 chattest.csproj 的以下程式碼中顯示的 UserSecretsId 元素,然後儲存檔案。Also add a UserSecretsId element as shown in the following code for chattest.csproj, and save the file.

    <Project Sdk="Microsoft.NET.Sdk.Web">
    <PropertyGroup>
        <TargetFramework>netcoreapp2.0</TargetFramework>
        <UserSecretsId>SignalRChatRoomEx</UserSecretsId>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
    </ItemGroup>
    <ItemGroup>
        <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
        <DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />
    </ItemGroup>
    </Project>    
    

將 Azure SignalR 新增至 Web 應用程式Add Azure SignalR to the web app

  1. 透過執行下列命令,將參考新增至 Microsoft.Azure.SignalR NuGet 套件:Add a reference to the Microsoft.Azure.SignalR NuGet package by running the following command:

     dotnet add package Microsoft.Azure.SignalR
    
  2. 執行下列命令以還原您專案的套件:Run the following command to restore packages for your project:

     dotnet restore
    
  3. 將名為 Azure:SignalR:ConnectionString 的祕密新增至祕密管理員。Add a secret named Azure:SignalR:ConnectionString to Secret Manager.

    此祕密將包含存取您 SignalR 服務資源的連接字串。This secret will contain the connection string to access your SignalR Service resource. Azure:SignalR:ConnectionString 為 SignalR 在建立連線時會尋找的預設組態金鑰。Azure:SignalR:ConnectionString is the default configuration key that SignalR looks for to establish a connection. 請以您 SignalR 服務資源的連接字串取代下列命令中的值。Replace the value in the following command with the connection string for your SignalR Service resource.

    您必須在和 .csproj 檔案相同的目錄中執行此命令。You must run this command in the same directory as the .csproj file.

    dotnet user-secrets set Azure:SignalR:ConnectionString "<Your connection string>"    
    

    祕密管理員將只會用來測試於本機裝載的 Web 應用程式。Secret Manager will be used only for testing the web app while it's hosted locally. 在稍後的教學課程中,您會將聊天 Web 應用程式部署至 Azure。In a later tutorial, you'll deploy the chat web app to Azure. 在 Web 應用程式部署至 Azure 之後,您將會使用應用程式設定,而非搭配祕密管理員儲存連接字串。After the web app is deployed to Azure, you'll use an application setting instead of storing the connection string with Secret Manager.

    此祕密可使用設定 API 來存取。This secret is accessed with the Configuration API. 在所有支援的平台上,組態 API 的組態名稱中都適用冒號 (:)。A colon (:) works in the configuration name with the Configuration API on all supported platforms. 請參閱取決於環境的組態See Configuration by environment.

  4. 開啟 Startup.cs 並更新 ConfigureServices 方法,以透過呼叫 services.AddSignalR().AddAzureSignalR() 來使用 Azure SignalR 服務:Open Startup.cs and update the ConfigureServices method to use Azure SignalR Service by calling the services.AddSignalR().AddAzureSignalR() method:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddSignalR().AddAzureSignalR();
    }
    

    透過不傳遞參數至 AddAzureSignalR(),此程式碼會針對 SignalR 服務資源連接字串使用預設組態金鑰。By not passing a parameter to AddAzureSignalR(), this code uses the default configuration key for the SignalR Service resource connection string. 預設組態金鑰為 Azure: SignalR:ConnectionStringThe default configuration key is Azure:SignalR:ConnectionString.

  5. 同時,透過在 Startup.cs 中以下列程式碼取代對 app.UseStaticFiles() 的呼叫並儲存檔案,來更新 Configure 方法。Also in Startup.cs, update the Configure method by replacing the call to app.UseStaticFiles() with the following code and save the file.

    app.UseFileServer();
    app.UseAzureSignalR(routes =>
    {
        routes.MapHub<Chat>("/chat");
    });
    

新增中樞類別Add a hub class

在 SignalR 中,中樞是一個核心元件,可公開由用戶端呼叫的一組方法。In SignalR, a hub is a core component that exposes a set of methods that can be called from the client. 在本節中,您會搭配兩個方法定義中樞類別:In this section, you define a hub class with two methods:

  • Broadcast:此方法會將訊息廣播至所有用戶端。Broadcast: This method broadcasts a message to all clients.
  • Echo:此方法會將訊息傳送回呼叫端。Echo: This method sends a message back to the caller.

這兩個方法都會使用由 ASP.NET Core SignalR SDK 所提供的 Clients 介面。Both methods use the Clients interface that the ASP.NET Core SignalR SDK provides. 此介面可讓您存取所有已連線的用戶端,以便將內容推送至用戶端。This interface gives you access to all connected clients, so you can push content to your clients.

  1. 在您的專案目錄中,新增名為 Hub 的資料夾。In your project directory, add a new folder named Hub. 將名為 Chat.cs 的新中樞程式碼檔案新增至這個新的資料夾。Add a new hub code file named Chat.cs to the new folder.

  2. 將下列程式碼新增至 Chat.cs 以定義中樞類別,然後儲存檔案。Add the following code to Chat.cs to define your hub class and save the file.

    如果您使用 chattest 之外的專案名稱,請更新此類別的命名空間。Update the namespace for this class if you used a project name that differs from chattest.

    using Microsoft.AspNetCore.SignalR;
    
    namespace chattest
    {
    
        public class Chat : Hub
        {
            public void BroadcastMessage(string name, string message)
            {
                Clients.All.SendAsync("broadcastMessage", name, message);
            }
    
            public void Echo(string name, string message)
            {
                Clients.Client(Context.ConnectionId).SendAsync("echo", name, message + " (echo from server)");
            }
        }
    }
    

新增 Web 應用程式的用戶端介面Add the client interface for the web app

此聊天室應用程式的用戶端使用者介面,將會由位於 wwwroot 目錄中名為 index.html 檔案內的 HTML 和 JavaScript 所組成。The client user interface for this chat room app will consist of HTML and JavaScript in a file named index.html in the wwwroot directory.

複製範例存放庫 (英文) 的 wwwroot 資料夾中 cssscripts 資料夾內的 index.html 檔案。Copy the index.html file, the css folder, and the scripts folder from the wwwroot folder of the samples repository. 將它們貼到您專案的 wwwroot 資料夾中。Paste them into your project's wwwroot folder.

這裡有 index.html 的主要程式碼:Here's the main code of index.html:

var connection = new signalR.HubConnectionBuilder()
                            .withUrl('/chat')
                            .build();
bindConnectionMessage(connection);
connection.start()
    .then(function () {
        onConnected(connection);
    })
    .catch(function (error) {
        console.error(error.message);
    });

index.html 中的程式碼會呼叫 HubConnectionBuilder.build(),以建立與 Azure SignalR 資源的 HTTP 連線。The code in index.html calls HubConnectionBuilder.build() to make an HTTP connection to the Azure SignalR resource.

如果連線成功,該連線會傳遞至 bindConnectionMessage,這會為針對用戶端的傳入內容推送新增事件處理常式。If the connection is successful, that connection is passed to bindConnectionMessage, which adds event handlers for incoming content pushes to the client.

HubConnection.start() 會開始與中樞進行通訊。HubConnection.start() starts communication with the hub. 然後 onConnected() 會新增按鈕事件處理常式。Then, onConnected() adds the button event handlers. 這些處理常式會使用連線來允許此用戶端將內容更新推送至所有已連線的用戶端。These handlers use the connection to allow this client to push content updates to all connected clients.

新增開發執行階段設定檔Add a development runtime profile

在本節中,您將會新增適用於 ASP.NET Core 的開發執行階段環境。In this section, you'll add a development runtime environment for ASP.NET Core. 如需詳細資訊,請參閱在 ASP.NET Core 中使用多個環境 (英文)。For more information, see Work with multiple environments in ASP.NET Core.

  1. 在專案中建立名為 Properties 的資料夾。Create a folder named Properties in your project.

  2. 將名為 launchSettings.json 的檔案新增至資料夾,並在檔案中加入以下內容,然後儲存檔案。Add a new file named launchSettings.json to the folder, with the following content, and save the file.

    {
        "profiles" : 
        {
            "ChatRoom": 
            {
                "commandName": "Project",
                "launchBrowser": true,
                "environmentVariables": 
                {
                    "ASPNETCORE_ENVIRONMENT": "Development"
                },
                "applicationUrl": "http://localhost:5000/"
            }
        }
    }
    

於本機建置並執行應用程式Build and run the app locally

  1. 若要使用 .NET Core CLI 來建置應用程式,請在命令殼層中執行下列命令:To build the app by using the .NET Core CLI, run the following command in the command shell:

     dotnet build
    
  2. 建置成功完成後,請執行以下命令以在本機執行 Web 應用程式:After the build successfully finishes, run the following command to run the web app locally:

     dotnet run
    

    該應用程式將會依照開發執行階段設定檔中的設定,於本機裝載在連接埠 5000 上:The app will be hosted locally on port 5000, as configured in our development runtime profile:

     E:\Testing\chattest>dotnet run
     Hosting environment: Development
     Content root path: E:\Testing\chattest
     Now listening on: http://localhost:5000
     Application started. Press Ctrl+C to shut down.    
    
  3. 開啟兩個瀏覽器視窗。Open two browser windows. 在每個瀏覽器中,前往 http://localhost:5000In each browser, go to http://localhost:5000. 系統將提示您輸入您的名稱。You're prompted to enter your name. 為兩個用戶端輸入用戶端名稱,然後使用 [Send] (傳送) 按鈕在兩個用戶端之間測試推送訊息內容。Enter a client name for both clients and test pushing message content between both clients by using the Send button.

    Azure SignalR 群組聊天的範例

清除資源Clean up resources

如果您準備繼續進行下一個教學課程,則可以保留在本快速入門中所建立的資源,並重複使用它們。If you'll continue to the next tutorial, you can keep the resources created in this quickstart and reuse them.

如果您已完成快速入門範例應用程式,可以刪除在此快速入門中建立的 Azure 資源以避免衍生費用。If you're finished with the quickstart sample application, you can delete the Azure resources created in this quickstart to avoid charges.

重要

刪除資源群組是無法回復的動作,而且會刪除該群組中的所有資源。Deleting a resource group is irreversible and includes all the resources in that group. 請確定您不會誤刪錯誤的資源群組或資源。Make sure that you don't accidentally delete the wrong resource group or resources. 如果您是在包含需保留資源的現有資源群組內部,建立用來裝載此範例的資源,則可以從每個資源刀鋒視窗中個別刪除每個資源,而不必刪除整個資源群組。If you created the resources for hosting this sample in an existing resource group that contains resources you want to keep, you can delete each resource individually from its blade instead of deleting the resource group.

登入 Azure 入口網站,然後選取 [資源群組] 。Sign in to the Azure portal and select Resource groups.

在 [依名稱篩選] 文字方塊中,輸入您資源群組的名稱。In the Filter by name text box, type the name of your resource group. 本快速入門的指示是使用名為 SignalRTestResources 的資源群組。The instructions for this quickstart used a resource group named SignalRTestResources. 在結果清單中的該資源群組上,選取 [...] > [刪除資源群組] 。On your resource group in the result list, select the ellipsis (...) > Delete resource group.

刪除資源群組的選取項目

系統將會要求您確認是否刪除資源群組。You're asked to confirm the deletion of the resource group. 輸入您資源群組的名稱以進行確認,然後選取 [刪除] 。Enter the name of your resource group to confirm, and select Delete.

不久後,系統便會刪除該資源群組及其所有的資源。After a few moments, the resource group and all of its resources are deleted.

後續步驟Next steps

在本快速入門中,您已建立新的 Azure SignalR 服務資源。In this quickstart, you created a new Azure SignalR Service resource. 然後會搭配 ASP.NET Core Web 應用程式使用它,以將內容更新即時推送至多個已連線的用戶端。You then used it with an ASP.NET Core web app to push content updates in real time to multiple connected clients. 若要深入了解如何使用 Azure SignalR 服務,請繼續進行下一個示範驗證的教學課程。To learn more about using Azure SignalR Service, continue to the tutorial that demonstrates authentication.