C#代码中如何创建Card

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/beastboy/article/details/100587976

C#代码中如何创建Card

Microsoft.Bot.Connector

Microsoft.Bot.Connector为微软官方package【Microsoft.Bot.Connector.dll】
在Bot/Connector/Message Extension中的消息都是通过Activity来承载的【命名空间Microsoft.Bot.Connector,对应的ContentType为application/vnd.microsoft.activity】,那么在Activity中如何添加Card对象呢?
谈到这里,其实又可以提到强大的App Studio了,因为它就提供生成Card预览和对应代码的功能。
话不多说,先说下这个功能:

  • 进入Card editor
    在这里插入图片描述
  • 选择Hero Card
    在这里插入图片描述
  • 选择csharp对应的tab,这里提供了Card对应json数据结构和C#对应的code snippet。有图上部分是我从代码中截出来的属性。
    下部分是preview效果。其实这个就已经足够我们做测试了。比如希望得到的Card是什么样的,然后进行编辑,实时看效果。
    当效果ok后,再放到代码工程里。
    在这里插入图片描述

CSharp代码示例

当然,这里是以Hero Card作为示例的。也可以按照实际情况,选择Thumbnail Card或者Adaptive Card。下边是生成Thumbnail Card,在实际项目中的部分代码:

        private static ComposeExtensionAttachment GetItemAttachment(ItemInfo item)
        {
            var card = new ThumbnailCard
            {
                Title = item.Name,
                Text = item.Description.Length > 20 ? item.Description.Substring(0, 20) : item.Description,
                Images = new List<CardImage> { new CardImage(item.Image) },
                Subtitle = item.Link,
                Tap = new CardAction() { Type = "postBack", Title = item.Name, Value = "https://docs.microsoft.com/en-us/MicrosoftTeams/teams-overview", Image = item.Image },
            };

            var starBtn = new CardAction() { Type = "messageBack", DisplayText = "Star", Title = "Star", Value = "{\"Id\":\"" + item.Id + "\",\"Star\":true}" };
            var updateItemBtn = new CardAction() { Type = "invoke", DisplayText = "Update " + item.Name, Title = "Update this item", Value = "{\"type\":\"task/fetch\",\"title\":\"Update\",\"Id\":\"" + item.Id + "\"}" };
            card.Buttons = new List<CardAction>() { starBtn, updateItemBtn };


            return card
                .ToAttachment()
                .ToComposeExtensionAttachment();
        }

框架代码提供了Card和Bot的attachment的方法,方便使用。

如果想看更多的示例代码,也可以上github上微软名下找找对应repository,有很多示例代码。或者有其他可用的repository也有蛮高的参考价值,比如https://github.com/Office365DevOps/microsoft-teams-templates。

如有问题,可以下方留言,共同探讨。

猜你喜欢

转载自blog.csdn.net/beastboy/article/details/100587976