You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Bot Framework的C#聊天机器人报错:Lambda表达式代码路径未返回有效值

解决Bot Framework中Startup.cs的代码路径返回错误

错误信息

C# 并非所有代码路径都返回类型为func<IserviceProvider,TestBot>的lambda表达式中的有效值

问题原因

你使用的AddBot<T>重载要求提供一个能返回Bot实例的委托,但当前代码仅配置了options参数,没有返回AlsayerBot的实例,导致编译器抛出此错误。

修正代码

services.AddBot<AlsayerBot>(options =>
{
    var conversationState = new ConversationState(new MemoryStorage());
    options.State.Add(conversationState);
    options.CredentialProvider = new ConfigurationCredentialProvider(configuration);
}, provider =>
{
    // 从服务容器获取依赖并实例化AlsayerBot
    var conversationState = provider.GetRequiredService<ConversationState>();
    return new AlsayerBot(conversationState);
});

优化方案(推荐)

先将ConversationState注册到服务容器,后续实例化Bot时可直接注入依赖:

// 注册ConversationState到服务容器
services.AddSingleton<ConversationState>(sp => new ConversationState(new MemoryStorage()));

services.AddBot<AlsayerBot>(options =>
{
    options.CredentialProvider = new ConfigurationCredentialProvider(configuration);
}, provider =>
{
    var conversationState = provider.GetRequiredService<ConversationState>();
    return new AlsayerBot(conversationState);
});

内容的提问来源于stack exchange,提问作者hamzahjazi98

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 22:36:33