2017-03-06 62 views
2

我試圖在Bot框架中的兩個對話框之間傳遞IList<Attachment>類型的對象。這裏是我的代碼看起來現在:如何在Microsoft Bot Framework中的對話框之間傳遞對象?

主對話框

[Serializable] 
public class CarouselCardsDialog : IDialog<object> 
{ 
    public async Task StartAsync(IDialogContext context) 
    { 
     context.Wait(this.MessageReceivedAsync); 
    } 

    public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result) 
    { 
     //This object, 'attachments' is what I need to pass to the child dialog. 
     IList<Attachment> attachments = GetCardsAttachments(); 
     context.Call(new CarouselDialog(attachments), ResumeAfterPrompt); 
    } 

    private async Task ResumeAfterPrompt(IDialogContext context, IAwaitable<string> result) 
    { 
     string input = await result; 
     await context.PostAsync(input); 
     context.Wait(MessageReceivedAsync); 
    } 

    private static IList<Attachment> GetCardsAttachments() 
    { 
     //Get a list of attachment 
    } 
} 

這是孩子對話。我想從CarouselCardsDialog附件列表傳遞給這個對象:

[Serializable] 
public class CarouselDialog : IDialog<string> 
{ 
    private IList<Attachment> _attachments; 

    public CarouselDialog(IList<Attachment> attachments) 
    { 
     _attachments = attachments; 
    } 

    public async Task StartAsync(IDialogContext context) 
    { 
     IMessageActivity reply = context.MakeMessage(); 
     reply.AttachmentLayout = AttachmentLayoutTypes.Carousel; 
     reply.Attachments = _attachments; 
     await context.PostAsync(reply); 
     context.Wait(MessageReceivedAsync); 
    } 

    public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result) 
    { 
     IMessageActivity activity = await result; 
     context.Done(activity.Text); 
    } 
} 

然而,當我運行此代碼,我得到這個錯誤:

Exception: Type 'Microsoft.Bot.Connector.Attachment' in Assembly 'Microsoft.Bot.Connector, Version=3.5.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable.

我在做什麼錯?有沒有解決的辦法?

+0

錯誤消息使得它聽起來像你的'附件'類需要[序列化],否則依賴它的類也不會是。 –

+0

@CSmith感謝您的意見。問題是Attachment類屬於框架,所以我認爲改變它並不現實。你知道是否有這樣的解決方法嗎? – artie

+0

您可以創建自己的類,將其標記爲可序列化並使用Attachment類中感興趣的值填充它。 –

回答

2

不確定異常,但是一種解決方法是爲所有需要製作附件的數據創建一個模型,然後將這些數據保存在上下文的UserData屬性中。

context.UserData.SetValue<MyModel>("AttachmentsModel", instanceOfModel); 

,然後檢索在這個模型中你的第二個對話框

MyModel model; 
context.UserData.TryGetValue<MyModel>("AttachmentsModel", out model); 

我想你也可以嘗試將一個IAttachment對象在此屬性,但模型會更好,因爲它不是真正爲舉行大的物體。