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

如何在MS Bot Framework中使用Azure Storage操作用户数据?旧方法替代咨询

Bot Framework + Azure Storage:旧状态访问方法的替代方案

嘿,我来帮你理清这个问题——那些旧的会话、用户数据访问原语(比如早年的StateClient、旧版BotState实现)确实已经彻底过时,完全不能再搭配Azure Storage使用了,微软早就停止了对这些API的支持,继续用只会遇到兼容性问题甚至功能失效。

不过别担心,现在有专门适配Azure Storage的现代替代方案,而且是Bot Framework官方推荐的最佳实践:

推荐的替代方案:使用Azure Storage状态适配器

目前Bot Framework提供了针对Azure Blob Storage和Table Storage的官方存储适配器,完美支持会话、用户状态的存储与管理,步骤如下:

  1. 安装依赖包
    先安装Microsoft.Bot.Builder.Azure这个NuGet包,它包含了所有Azure Storage相关的状态处理类。

  2. 初始化Azure Storage实例
    根据你选择的存储类型(Blob或Table),创建对应的存储对象:

    // Blob Storage示例
    var blobStorage = new AzureBlobStorage(
        "<你的Azure Storage连接字符串>",
        "<存储状态数据的容器名称>"
    );
    
    // 或者Table Storage示例
    var tableStorage = new AzureTableStorage(
        "<你的Azure Storage连接字符串>",
        "<存储状态数据的表名称>"
    );
    
  3. 配置会话/用户状态
    用上面的存储实例创建ConversationState和UserState对象,并注入到你的Bot服务中:

    // 以Blob Storage为例
    var conversationState = new ConversationState(blobStorage);
    var userState = new UserState(blobStorage);
    
    // 注入到依赖注入容器
    services.AddSingleton(conversationState);
    services.AddSingleton(userState);
    
  4. 在Bot逻辑中访问状态数据
    通过StatePropertyAccessor来安全地获取和修改会话/用户数据,最后记得保存更改:

    // 在Bot类中注入UserState
    private readonly UserState _userState;
    private readonly IStatePropertyAccessor<UserProfile> _userProfileAccessor;
    
    public YourBot(UserState userState)
    {
        _userState = userState;
        // 创建用户状态属性访问器
        _userProfileAccessor = _userState.CreateProperty<UserProfile>("UserProfile");
    }
    
    public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default)
    {
        // 获取用户状态数据,不存在则初始化
        var userProfile = await _userProfileAccessor.GetAsync(turnContext, () => new UserProfile());
    
        // 操作用户数据,比如更新用户名
        userProfile.UserName = "John Doe";
    
        // 保存状态更改
        await _userState.SaveChangesAsync(turnContext);
    
        // 其他对话逻辑...
    }
    

这种方式不仅完全兼容Azure Storage,还具备更好的性能、可靠性,同时能和Bot Framework的最新特性(比如自适应对话、状态快照)无缝集成,是目前的标准做法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:21:36