将BotState替换为用于保存用户数据的自定义实现

时间:2018-03-23 09:38:52

标签: botframework azure-bot-service

以前我使用StateClient对象保存UserData,但由于不推荐使用,我已经实现了一个将ConversationData保存在私有数据库中的解决方案。使用botCredentials:`

将UserData设置在对话框上下文之外
var botCred = new MicrosoftAppCredentials(
                    BotConfiguration.Cfg.MicrosoftAppId,
                    BotConfiguration.Cfg.MicrosoftAppPassword);
                var stateClient = new StateClient(botCred);
                BotState botState = new BotState(stateClient);
                BotData botData = new BotData(eTag: "*");
                botData.SetProperty<string>("LastName", lastName);
                botData.SetProperty<string>("FirstName", firstName);
                stateClient.BotState.SetUserData("webchat", userId, botData);

问题在于这是在外部控制器中完成的。

如何使用我的自定义数据库进行存储以获得相同的结果?

谢谢

1 个答案:

答案 0 :(得分:0)

我认为当您无法访问上下文对象时,您正在询问如何读取/写入状态数据。在这种情况下,您将使用类似以下代码的内容:

public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
    if (activity.Type == ActivityTypes.Message)
    {

            var message = activity as IMessageActivity;
            using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
            {
                var botDataStore = scope.Resolve<IBotDataStore<BotData>>();
                var key = Address.FromActivity(message);

                ConversationReference r = new ConversationReference();
                var userData = await botDataStore.LoadAsync(key, BotStoreType.BotUserData, CancellationToken.None);

                userData.SetProperty("key 1", "value1");
                userData.SetProperty("key 2", "value2");

                await botDataStore.SaveAsync(key, BotStoreType.BotUserData, userData, CancellationToken.None);
                await botDataStore.FlushAsync(key, CancellationToken.None);
            }
            await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
    }
}