Core Bot 样本真的缺少令牌服务器吗?该示例称为 CORE BOT,我猜每个 bot 都需要一个令牌服务器?!
不,不是真的。如果您正在构建自己的网络聊天客户端,就像在网络聊天示例中一样,您可以拥有一个令牌服务器来交换令牌的秘密。但是,如果您不是在构建自己的网络聊天,或者您不关心用秘密交换令牌,或者您想使用任何其他渠道,那么您就不需要一个。
话虽如此,我在 C# here 中有一个有效的秘密->令牌交换。就像 webchat repo 中的节点版本一样。这些是我为将该示例从节点转换为 C# 所做的更改:
在我的 html 文件中:
<body>
<h2>Index??</h2>
<div id="webchat" role="main" />
<script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
<script>
(async function () {
const res = await fetch('/directline/token', { method: 'POST' });
const { token } = await res.json();
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token }),
}, document.getElementById('webchat'));
})();
</script>
</body>
为了捕捉那个 POST 请求,我必须向机器人添加一些东西。在启动类中,我需要确保看到我的令牌模型:
services.Configure<DLSModel>(Configuration.GetSection("DirectLine"));
然后,我将 DSLModel 添加到我的模型中
模型本身非常简单:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace JJDirectLineBot.Models
{
public class DLSModel
{
public string DirectLineSecret { get; set; }
}
}
基本上,所有这些都说“在她的应用设置中寻找她的直通密码”。我确信有一种更简单的方法可以到达那里,但我就是这样做的。
然后,您需要一个控制器来实际发出请求:
namespace JJDirectLineBot.Controllers
{
public class TokenController : ControllerBase
{
private readonly IOptions<DLSModel> dlSecret;
public TokenController(IOptions<DLSModel> dls)
{
dlSecret = dls;
}
[Route("/directline/token")]
[HttpPost]
public async Task<string> TokenRequest()
{
var secret = dlSecret.Value.DirectLineSecret;
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(
HttpMethod.Post,
$"https://directline.botframework.com/v3/directline/tokens/generate");
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", secret);
var userId = $"dl_{Guid.NewGuid()}";
request.Content = new StringContent(
JsonConvert.SerializeObject(
new { User = new { Id = userId } }),
Encoding.UTF8,
"application/json");
var response = await client.SendAsync(request);
string token = string.Empty;
if (response.IsSuccessStatusCode)
{
var body = await response.Content.ReadAsStringAsync();
return body;
}
else
{
//Error();
return token;
}
}
}
}