您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

创建连接到 Direct Line 应用服务扩展的 .NET 客户端Create .NET Client to Connect to Direct Line App Service Extension

适用于: SDK v4APPLIES TO: SDK v4

本文介绍如何使用 C# 创建连接到 Direct Line 应用服务扩展的 .NET 客户端。This article describes how to create a .NET client in C# which connects to the direct line app service extension. 另请参阅此配套文章:为扩展配置 .NET 机器人Please, also read this companion article Configure .NET bot for extension.

获取直接行密钥Get Direct Line secret key

  1. 在浏览器中,导航到 Azure 门户In your browser, navigate to the Azure portal

  2. 在 Azure 门户中,找到“Azure 机器人服务”资源In the Azure portal, locate your Azure Bot Service resource

  3. 单击 " 频道 " 配置机器人的频道Click on Channels to configure the bot's channels

  4. 单击“Direct Line”通道将其启用(如果尚未启用)。If it is not already enabled, click on the Direct Line channel to enable it.

  5. 如果该通道已启用,请在“连接到通道”表的“Direct Line”行中单击“编辑”链接。 If it is already enabled, in the Connect to channels table click on the Edit link on the Direct Line row.

  6. 滚动到“站点”部分。Scroll to the Sites section. 通常会有一个“默认站点”,除非已将其删除或重命名。There is typically a Default Site unless you have deleted or renamed it.

  7. 单击“显示链接”显示其中的一个键,然后复制并保存其值。 Click on the Show link to reveal one of the keys, then copy and save its value. 你将在 创建 c # 直接连线客户端部分中使用此值。You will use this value in the section Create a C# Direct Line Client.

    应用服务扩展密钥

备注

此值是 Direct Line 客户端机密,用于连接到 Direct Line 应用服务扩展。This value is your direct line client secret used to connect to direct line app service extension. 如果需要,还可以创建其他站点并使用这些机密值。You can create additional sites if you'd like and use those secret values as well.

添加预览 NuGet 包源Add the preview NuGet package source

可以在 NuGet 源中找到创建 C# Direct Line 客户端所需的预览版 NuGet 包。The preview NuGet packages needed to create a C# Direct line client can be found in a NuGet feed.

  1. 在 Visual Studio 中导航到“工具”->“选项”菜单项。 In Visual Studio navigate to the Tools->Options menu item.
  2. 选择“NuGet 包管理器”->“包源”项。 Select the NuGet Package Manager->Package Sources item.
  3. 单击“+”按钮添加新的包源,其值如下:Click on the + button to add a new package source with these values:
  4. 单击“更新”按钮,保存这些值。 Click on the Update button to save the values.
  5. 单击“确定”, 退出“包源”配置。Click OK to exit the Package Sources configuration.

创建 c # 直接连线客户端Create a C# Direct Line client

与 Direct Line 应用服务扩展进行的交互的发生方式不同于传统的 Direct Line,因为大多数通信通过 WebSocket 进行。Interactions with the direct line app service extension happen differently than traditional Direct Line because most communication happens over a WebSocket. 更新的 Direct Line 客户端包含的帮助程序类可以用来打开和关闭 WebSocket、通过 WebSocket 发送命令,以及接收从机器人返回的活动。The updated direct line client includes helper classes for opening and closing a WebSocket, sending commands through the WebSocket, and receiving Activities back from the bot. 此部分介绍如何创建一个简单的用来与机器人交互的 C# 客户端。This section describes how to create a simple C# client to interact with a bot.

  1. 在 Visual Studio 中创建新的 .NET Core 2.2 控制台应用程序项目。In Visual Studio, create a new .NET Core 2.2 console application project.

  2. DirectLine 客户端 NuGet 添加到项目Add the DirectLine client NuGet to your project

  3. 创建客户端并使用机密生成令牌。Create a client and generate a token using a secret. 此步骤与构建任何其他的 C# Direct Line 客户端的步骤相同,只是需要用在机器人中的终结点会追加 .bot/ 路径,如下所示。This step is the same as building any other C# Direct Line client except the endpoint you need use in your bot,appended with the .bot/ path as shown next. 请勿忘记结尾的 /Do not forget the ending /.

    string endpoint = "https://<your_bot_name>.azurewebsites.net/.bot/";
    string secret = "<your_bot_direct_line_secret_key>";
    
    var tokenClient = new DirectLineClient(
        new Uri(endpoint),
        new DirectLineClientCredentials(secret));
    var conversation = await tokenClient.Tokens.GenerateTokenForNewConversationAsync();
    

    请注意以下内容:Notice the following:

    • 终结点值是在将机器人部署到 Azure 时获得的机器人 URL。The endpoint value is the bot URL you obtained when you deployed the bot to Azure. 有关详细信息,请参阅为扩展配置 .NET 机器人For more information, see Configure .NET bot for extension.
    • 显示为 YOUR_BOT_SECRET 的机密值为之前从站点部分 保存的值。The secret value shown as YOUR_BOT_SECRET is the value you saved earlier from the sites section.
  4. 通过生成令牌获得聊天引用以后,即可使用该聊天 ID 打开一个在 DirectLineClient 上有新 StreamingConversations 属性的 WebSocket。Once you have a conversation reference from generating a token, you can use this conversation ID to open a WebSocket with the new StreamingConversations property on the DirectLineClient. 为此,你需要创建一个回调。当机器人需要向客户端发送 ActivitySets 时,就会调用该回调。To do this you need to create a callback that will be invoked when the bot wants to send ActivitySets to the client:

    public static void ReceiveActivities(ActivitySet activitySet)
    {
        if (activitySet != null)
        {
            foreach (var a in activitySet.Activities)
            {
                if (a.Type == ActivityTypes.Message && a.From.Id.Contains("bot"))
                {
                    Console.WriteLine($"<Bot>: {a.Text}");
                }
            }
        }
    }
    
  5. 现在,你已准备好 StreamingConversations 使用会话的令牌、和回调打开属性上的 WebSocket conversationId ReceiveActivitiesNow you are ready to open the WebSocket on the StreamingConversations property using the conversation's token, conversationId, and your ReceiveActivities callback:

    var client = new DirectLineClient(
        new Uri(endpoint),
        new DirectLineClientCredentials(conversation.Token));
    
    await client.StreamingConversations.ConnectAsync(
        conversation.ConversationId,
        ReceiveActivities);
    
  6. 现在可以使用客户端来开始聊天并向机器人发送 ActivitiesThe client can now be used to start a conversation and send Activities to the bot:

    
    var startConversation = await client.StreamingConversations.StartConversationAsync();
    var from = new ChannelAccount() { Id = "123", Name = "Fred" };
    var message = Console.ReadLine();
    
    while (message != "end")
    {
        try
        {
            var response = await client.StreamingConversations.PostActivityAsync(
                startConversation.ConversationId,
                new Activity()
                {
                    Type = "message",
                    Text = message,
                    From = from
                });
        }
        catch (OperationException ex)
        {
            Console.WriteLine(
                $"OperationException when calling PostActivityAsync: ({ex.StatusCode})");
        }
        message = Console.ReadLine();
    }