显然,您的 Azure 应用服务没有在托管代码的 Azure 应用服务的 CORS 设置中正确配置 CORS。我在这里用详细的步骤解决了类似的问题,请尝试看看它是否对您有帮助。
似乎 URL 有问题:
https://csharpbotdw.azurewebsites.net/directline/token
你得到了 directLine 令牌。每次调用此 URL 时都会出现 404 错误,似乎那里没有这样的 API。
如果您尚未在代码中实现此类 API,请在您的 .net Framework 项目中尝试以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Newtonsoft.Json;
namespace CoreBot.Controllers
{
[Route("api/token")]
public class TokenController : ApiController
{
public async Task<IHttpActionResult> token()
{
var secret = "<your bot channel directline secret>";
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(
HttpMethod.Post,
$"https://directline.botframework.com/v3/directline/tokens/generate");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secret);
var userId = $"dl_{Guid.NewGuid()}";
request.Content = new StringContent(
Newtonsoft.Json.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();
token = JsonConvert.DeserializeObject<DirectLineToken>(body).token;
}
var config = new ChatConfig()
{
token = token,
userId = userId
};
return Ok(config);
}
}
public class DirectLineToken
{
public string conversationId { get; set; }
public string token { get; set; }
public int expires_in { get; set; }
}
public class ChatConfig
{
public string token { get; set; }
public string userId { get; set; }
}
}
要将其集成到您的项目中,请在项目的控制器文件夹下创建一个
TokenController.cs
文件并将上面的代码粘贴到其中:
并且在您将项目发布到 Azure 后,您将能够通过 URL :
https://csharpbotdw.azurewebsites.net/api/token
通过 post 方法获取令牌。
启用 CORS 并将代码发布到 Azure 后,您可以使用 HTML 代码连接到您的机器人:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Web Chat: Minimal bundle with Markdown</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdn.botframework.com/botframework-webchat/latest/webchat-minimal.js"></script>
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
}
#webchat {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
(async function() {
const res = await fetch('https://csharpbotdw.azurewebsites.net/api/token', { method: 'POST' });
const { token } = await res.json();
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({ token })
},
document.getElementById('webchat')
);
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html>
您必须在运行 csharpbotdw 服务的应用程序服务的 CORS 菜单中的已批准来源列表中添加调用域。
如果 DirectLine 或 WebChat 被创建为“Bot Channel Registration”,下面的代码将起作用。
(async()=>{
const styleOptions = {
bubbleBackground: 'rgba(0, 0, 255, .1)',
bubbleFromUserBackground: 'rgba(0, 255, 0, .1)',
rootHeight: '100%',
rootWidth: '50%',
botAvatarInitials: 'WC',
userAvatarInitials: 'WW',
};
var response = {};
const body = {
"user": {
"id": "George",
"name": "George"
},
"trustedOrigins": [
"http://localhost:5500"
]
}
const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', {
method: 'POST' ,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
Authorization: "Bearer <<YOUR_SECRET>>",
},
body:JSON.stringify(body)
}).then((response) => response.json())
.then((data) => response = data);
const tokenString = response.token;
console.log("Token " , tokenString );
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({
token: tokenString
}),
username: 'George',
locale: 'en-US',
styleOptions
},
document.getElementById('webchat')
);
})();