如何在Bot Composer中添加并调用C# Waterfall Dialog
Composer项目集成C# Waterfall Dialog的可行性与实现方案
这个方案是完全可行的,已有不少开发者在实际项目中实现了Composer自适应对话+传统Waterfall Dialog的混合开发模式,用来弥补Composer在复杂数据收集、自定义逻辑处理上的局限。
核心实现步骤
打开Composer生成的C#项目
Composer会将可视化编排的对话生成对应的C#代码,你可以直接在Visual Studio中打开Composer项目目录下generated\csharp路径里的解决方案文件。创建自定义Waterfall Dialog
新建一个继承自ComponentDialog的类,定义瀑布步骤来处理自适应卡片的数据收集和后续逻辑。示例代码如下:using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Dialogs; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; public class CardDataHandlerDialog : ComponentDialog { public static readonly string DialogId = "CardDataHandlerDialog"; public CardDataHandlerDialog() : base(DialogId) { var waterfallSteps = new WaterfallStep[] { ValidateCardDataAsync, CollectAdditionalInfoAsync, FinalizeProcessAsync }; AddDialog(new WaterfallDialog("cardDataWaterfall", waterfallSteps)); AddDialog(new TextPrompt("textPrompt")); } private async Task<DialogTurnResult> ValidateCardDataAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { // 接收从自适应卡片提交的原始数据 var cardSubmission = stepContext.Options as Dictionary<string, object>; // 自定义数据验证逻辑 if (!cardSubmission.ContainsKey("userEmail") || string.IsNullOrEmpty(cardSubmission["userEmail"].ToString())) { await stepContext.Context.SendActivityAsync("请在卡片中填写有效的邮箱地址", cancellationToken: cancellationToken); return await stepContext.ReplaceDialogAsync(DialogId, cardSubmission, cancellationToken); } await stepContext.Context.SendActivityAsync($"卡片数据验证通过:邮箱 {cardSubmission["userEmail"]}", cancellationToken: cancellationToken); return await stepContext.NextAsync(cardSubmission, cancellationToken); } private async Task<DialogTurnResult> CollectAdditionalInfoAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { var validatedData = stepContext.Result as Dictionary<string, object>; return await stepContext.PromptAsync( "textPrompt", new PromptOptions { Prompt = MessageFactory.Text("请提供你的联系电话:") }, cancellationToken); } private async Task<DialogTurnResult> FinalizeProcessAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { var phoneNumber = stepContext.Result as string; await stepContext.Context.SendActivityAsync($"流程完成,已记录你的联系方式:{phoneNumber}", cancellationToken: cancellationToken); return await stepContext.EndDialogAsync(cancellationToken: cancellationToken); } }注册并调用自定义Dialog
- 在项目的
Startup.cs中注册自定义Dialog:services.AddSingleton<CardDataHandlerDialog>(); - 在Composer中触发调用:
可以在Composer的对话流程里添加BeginDialog动作,指定自定义Dialog的ID(即CardDataHandlerDialog.DialogId),并将自适应卡片的提交数据作为参数传入。也可以在Bot的OnTurnAsync方法中,根据消息类型(比如检测到自适应卡片的Value提交)主动触发Dialog。
- 在项目的
关键注意事项
- 确保Bot Framework SDK版本一致:Composer生成的项目依赖特定版本的SDK,自定义Dialog的代码要使用相同版本的SDK包,避免兼容性问题。
- 状态管理一致性:Composer的自适应对话和传统Dialog共享对话状态,需确保状态读写逻辑不冲突,调试时重点跟踪
DialogState的变化。 - 数据传递准确性:从自适应卡片到Waterfall Dialog的参数传递要确保类型匹配,避免空引用或类型转换错误。
内容的提问来源于stack exchange,提问作者piotr
相关产品推荐
相关产品推荐

