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

使用C# Bot Framework存储状态到Azure Blob时遇序列化绑定错误

Bot Framework 4.19.2 状态存储到Azure Blob时的序列化类型错误问题

我使用C#开发Bot Framework,通过版本为4.19.2的NuGet包Microsoft.Bot.Builder.Azure.Blobs将机器人状态保存到Azure Blob存储。我的Startup.cs代码如下:

var storage = new BlobsStorage(
    "connectionstring",
    "containername"
);

var userState = new UserState(storage);
services.AddSingleton(userState);

var conversationState = new ConversationState(storage);
services.AddSingleton(conversationState);

运行时遇到如下错误:

System.InvalidOperationException: Unable to find the following types in the 'AllowedTypes' collection.
Please provide the 'AllowedTypesSerializationBinder' in the custom 'JsonSerializerSettings' instance, with the list of types to allow.

官方给出的示例配置代码:

new JsonSerializerSettings
{
    SerializationBinder = new AllowedTypesSerializationBinder(
        new List<Type>
        {
            typeof(PromptOptions),
            typeof(DialogInstance),
            typeof(DialogState),
        }),
}

另外我发现Azure Blob容器中已经生成了对应的Blob文件。


解决方法

Bot Framework 4.19+版本出于安全考虑,强制要求显式指定允许序列化的类型,以此防范反序列化漏洞。你需要在初始化BlobsStorage时传入包含AllowedTypesSerializationBinder的自定义序列化配置,具体步骤如下:

  1. 整理所有需要序列化的类型:包括框架内置的状态相关类型,以及你自己定义的用户状态、对话状态实体(如果有嵌套类型也要一并加入)
  2. 创建JsonSerializerSettings并配置SerializationBinder
  3. 将配置好的序列化设置传入BlobsStorage构造函数

修改后的Startup.cs代码示例:

// 定义允许序列化的类型列表
var allowedTypes = new List<Type>
{
    // 框架内置必要类型
    typeof(PromptOptions),
    typeof(DialogInstance),
    typeof(DialogState),
    // 添加你自定义的状态类型,例如:
    // typeof(MyCustomUserState),
    // typeof(MyCustomConversationState),
    // typeof(MyNestedStateType)
};

// 配置序列化设置
var serializerSettings = new JsonSerializerSettings
{
    SerializationBinder = new AllowedTypesSerializationBinder(allowedTypes)
};

// 初始化Blob存储时传入序列化配置
var storage = new BlobsStorage(
    "connectionstring",
    "containername",
    jsonSerializerSettings: serializerSettings
);

var userState = new UserState(storage);
services.AddSingleton(userState);

var conversationState = new ConversationState(storage);
services.AddSingleton(conversationState);

说明:确保所有需要持久化到Blob的类型都被添加到allowedTypes列表中,否则仍会触发相同的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 05:27:23