Directline没有针对Azure Bot Services的响应,并且被CORS策略阻止 [英] No response from Directline for Azure Bot Services and blocked by CORS policy
问题描述
我使用了
将此集成到您的项目,请在项目的控制器文件夹下创建一个 TokenController.cs
文件,并将上面的代码粘贴到其中:
您将能够通过URL获得令牌: https://csharpbotdw.azurewebsites.net/api/token <在将项目发布到Azure之后,通过邮寄方法获取/ code>。
在本地测试结果:
启用CORS并将代码发布到Azure之后,您可以使用HTML代码连接到您的机器人:
< html xmlns = http://www.w3.org/1999/xhtml> < head runat = server> < title>网络聊天:带有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,正文{高度:100%; } body {margin:0; } #webchat {高度:100%;宽度: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();窗口.WebChat.renderWebChat({directLine:window.WebChat.createDirectLine({token})},document.getElementById('webchat')); document.querySelector('#webchat> *')。focus();})( ).catch(err => console.error(err)); < / script> < / body> < / html>
I had use the Bot Services sample from Microsoft Sample for Bot Services.
After I debug, the web page does not shown any thing. Here with my source code:
<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/directline/token', { method: 'POST' });
const { token } = await res.json();
const markdownIt = window.markdownit();
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({ token })
},
document.getElementById('webchat')
);
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html>
I only saw the error mention
Access to fetch at 'https://csharpbotdw.azurewebsites.net/directline/token' from origin 'http://localhost:63191' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. [http://localhost:63191/Test13122019]
Obviously , your Azure app service has not configured CORS correctly in the CORS setting of your Azure app service which hosts your codes. I solved a similar issue with detailed steps here, pls have a try to see if it is helpful for you.
Seems there is something wrong with the URL : https://csharpbotdw.azurewebsites.net/directline/token
that you get your directLine token. Each time I call this URL I got an 404 error, seems there is no such API there.
If you haven't implemented such API in your code, try the code below in your .net framework project :
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; }
}
}
You can get bot channel directline secret here :
To integrate this into your project, pls create a TokenController.cs
file under your controller folder in your project and paste the code above into it:
And you will be able to get token via URL :https://csharpbotdw.azurewebsites.net/api/token
by post method after you publish your project to Azure.
Test result on my local :
You can use the HTML code to connect to your bot after you enabled CORS and publish your code to Azure :
<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>
这篇关于Directline没有针对Azure Bot Services的响应,并且被CORS策略阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!