BotBuilder CustomRecognizer无法工作,Parse方法未被调用求助
解决CustomRecognizer.Parse方法未被调用的问题
嘿,我之前也碰到过这个糟心的问题!CustomRecognizer的Parse方法没被触发,通常是几个常见的配置或逻辑问题导致的,咱们一步步排查解决:
1. 确认自定义识别器已正确注册
很多时候是忘了把CustomRecognizer添加到依赖注入容器或者对话集合里,导致Bot根本找不到它。举个代码示例:
- 在
ConfigureServices中注册识别器:
services.AddSingleton<IRecognizer>(sp => new CustomRecognizer());
- 如果是和Dialog一起使用,要确保DialogSet关联了这个识别器:
var dialogs = new DialogSet(conversationState.CreateProperty<DialogState>("DialogState")); dialogs.Add(new LuisDialog<object>(new CustomRecognizer()));
2. 检查基类实现与方法触发逻辑
Parse方法通常是Recognizer基类内部调用的,对外暴露的是RecognizeAsync方法。如果你的自定义识别器继承自错误的基类,或者没正确实现RecognizeAsync,就不会触发Parse。建议直接实现IRecognizer接口:
public class CustomRecognizer : IRecognizer { public async Task<RecognizerResult> RecognizeAsync(ITurnContext turnContext, CancellationToken cancellationToken = default) { // 这里可以直接写你的解析逻辑(替代Parse方法的功能) var result = new RecognizerResult(); // 示例:添加自定义意图 result.Intents.Add("MyCustomIntent", new IntentScore { Score = 1.0 }); return result; } public async Task<T> RecognizeAsync<T>(ITurnContext turnContext, CancellationToken cancellationToken = default) where T : IRecognizerConvert, new() { var baseResult = await RecognizeAsync(turnContext, cancellationToken); var convertedResult = new T(); convertedResult.Convert(baseResult); return convertedResult; } }
3. 确保对话流程中主动调用识别器
就算注册了识别器,如果在Bot的消息处理逻辑里没主动调用RecognizeAsync,Parse(或自定义解析逻辑)也不会触发。比如在OnMessageActivityAsync里:
protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken) { // 获取注册的识别器实例 var customRecognizer = _services.GetRequiredService<IRecognizer>(); // 调用识别方法触发解析 var recognitionResult = await customRecognizer.RecognizeAsync(turnContext, cancellationToken); // 处理识别结果 var topIntent = recognitionResult.GetTopScoringIntent(); await turnContext.SendActivityAsync($"触发的意图:{topIntent.intent},置信度:{topIntent.score}", cancellationToken: cancellationToken); }
4. 排查中间件或其他识别器的干扰
如果你的Bot同时配置了LUIS、QnAMaker等其他识别器,或者添加了自定义中间件,可能会导致请求被提前处理,没走到你的自定义识别器。可以尝试:
- 暂时禁用其他识别器,单独测试
CustomRecognizer - 移除非必要的中间件,验证是否能触发解析逻辑
内容的提问来源于stack exchange,提问作者Ma3yTa
相关产品推荐
相关产品推荐

