在MVC应用中嵌入Azure C#表单流机器人(非iframe)求可用示例
当然有!下面是一个完整的自定义MVC聊天窗口嵌入Direct Line机器人的实现示例,完全不需要iframe,你可以直接适配到你的项目里:
实现步骤
1. 安装必要的NuGet包
在你的MVC项目中,通过NuGet安装Direct Line的SDK包,打开Package Manager Console执行:
Install-Package Microsoft.Bot.Connector.DirectLine -Version 3.0.0
(也可以选择最新稳定版本,3.0.0是经过广泛验证的版本)
2. 创建Chat控制器
新建一个ChatController,负责生成Direct Line令牌(避免前端暴露密钥,更安全),并将必要参数传递给视图:
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Bot.Connector.DirectLine; namespace YourMvcAppNamespace.Controllers { public class ChatController : Controller { // 替换为你的Direct Line密钥(从Azure门户机器人资源的"Channels"->"Direct Line"中获取) private readonly string _directLineSecret = "YOUR_DIRECT_LINE_SECRET"; // 替换为你的机器人ID(Azure门户机器人资源的"配置"页面中可以找到) private readonly string _botId = "YOUR_BOT_ID"; public async Task<IActionResult> Index() { // 使用密钥生成会话令牌 var directLineClient = new DirectLineClient(_directLineSecret); var tokenResponse = await directLineClient.Tokens.GenerateTokenForNewConversationAsync(); // 将令牌和机器人ID传递给视图 ViewBag.DirectLineToken = tokenResponse.Token; ViewBag.BotId = _botId; return View(); } } }
3. 自定义聊天视图(Chat/Index.cshtml)
创建视图文件,包含自定义的聊天窗口HTML、样式,以及和机器人通信的JavaScript逻辑:
HTML结构
<div id="chat-container"> <div id="messages-container"></div> <div id="input-container"> <input type="text" id="message-input" placeholder="输入消息..." /> <button id="send-button">发送</button> </div> </div>
自定义CSS样式
#chat-container { width: 420px; height: 550px; border: 1px solid #e0e0e0; border-radius: 10px; display: flex; flex-direction: column; margin: 30px auto; box-shadow: 0 2px 8px rgba(0,0,0,0.1); } #messages-container { flex: 1; padding: 15px; overflow-y: auto; background-color: #fafafa; } .message { margin-bottom: 12px; padding: 10px 14px; border-radius: 20px; max-width: 75%; word-wrap: break-word; } .user-message { background-color: #0078d4; color: #fff; margin-left: auto; } .bot-message { background-color: #fff; color: #333; margin-right: auto; border: 1px solid #eee; } #input-container { display: flex; padding: 12px; border-top: 1px solid #eee; background-color: #fff; } #message-input { flex: 1; padding: 10px 16px; border: 1px solid #ddd; border-radius: 25px; outline: none; font-size: 14px; } #send-button { margin-left: 10px; padding: 10px 20px; background-color: #0078d4; color: #fff; border: none; border-radius: 25px; cursor: pointer; font-size: 14px; transition: background-color 0.2s; } #send-button:hover { background-color: #005a9e; }
JavaScript通信逻辑
<script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script> <script> // 从视图获取令牌和机器人ID const directLineToken = '@ViewBag.DirectLineToken'; const botId = '@ViewBag.BotId'; // 初始化Direct Line连接 const directLine = window.WebChat.createDirectLine({ token: directLineToken }); // 监听机器人发送的消息 directLine.activity$.subscribe(activity => { // 只处理机器人发送的消息(排除用户自己的消息) if (activity.type === 'message' && activity.from.id === botId) { displayMessage(activity.text, 'bot-message'); } }); // 发送消息到机器人 function sendMessage() { const input = document.getElementById('message-input'); const text = input.value.trim(); if (!text) return; // 先在界面显示用户消息 displayMessage(text, 'user-message'); // 发送消息到机器人 directLine.postActivity({ type: 'message', text: text, from: { id: 'user-' + Date.now() } // 生成唯一用户标识 }).subscribe(); // 清空输入框 input.value = ''; } // 将消息渲染到聊天窗口 function displayMessage(text, className) { const messagesContainer = document.getElementById('messages-container'); const messageElement = document.createElement('div'); messageElement.className = `message ${className}`; messageElement.textContent = text; messagesContainer.appendChild(messageElement); // 自动滚动到最新消息 messagesContainer.scrollTop = messagesContainer.scrollHeight; } // 绑定发送事件:按钮点击 + 回车键 document.getElementById('send-button').addEventListener('click', sendMessage); document.getElementById('message-input').addEventListener('keypress', e => { if (e.key === 'Enter') sendMessage(); }); </script>
4. 配置路由(可选)
确保你的MVC路由能正确访问Chat控制器,在Program.cs(.NET Core 6+)或Startup.cs中添加默认路由:
// Program.cs示例 app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
现在访问/Chat/Index就能看到自定义的聊天窗口了。
额外注意事项
- 安全提示:绝对不要在前端代码中直接暴露Direct Line密钥,一定要通过后端生成会话令牌,示例中已经采用了这种安全方式。
- 自定义扩展:如果你的表单流机器人使用了自适应卡片等富媒体内容,可以在
activity$.subscribe中处理activity.attachments,使用WebChat的renderAttachment方法来渲染卡片。 - 样式定制:你可以完全修改CSS来匹配你的MVC应用的设计风格,调整窗口大小、颜色、字体等。
- 错误处理:可以为Direct Line连接添加错误监听,处理连接中断、消息发送失败等情况,提升用户体验。
内容的提问来源于stack exchange,提问作者Sonali
相关产品推荐
相关产品推荐

