0

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]
Eng Soon Cheah
  • 257
  • 1
  • 10
  • 42

3 Answers3

3

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 : enter image description here enter image description 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: enter image description here

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 : enter image description here

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>
Stanley Gong
  • 11,522
  • 1
  • 8
  • 16
  • I had try it but still no response, is that my source code issue in HTML page? and also the Chat Bot Source Code? May you share the last screen source code? – Eng Soon Cheah Dec 17 '19 at 05:50
  • Hi @EngSoonCheah, is there any exception information on your side if there is no response? I tried to call url https://csharpbotdw.azurewebsites.net/directline/token , but got a 404 error, so may I know have you implemented such api in your Chat Bot Source Code? – Stanley Gong Dec 17 '19 at 06:01
  • Stanley, I no implement such api in my source code. I just follow the sample https://github.com/Microsoft/BotFramework-WebChat/tree/master/samples/01.a.getting-started-full-bundle , by the way which URL api should I use? – Eng Soon Cheah Dec 17 '19 at 06:18
  • Hi @EngSoonCheah, I have updated my answer, pls let me know if you need further assistance . – Stanley Gong Dec 17 '19 at 06:23
  • Hi @EngSoonCheah , you should implement that API yourself in your bot code, if you dont know how to do that , just let me know your programming language , I'll write a demo for you. – Stanley Gong Dec 17 '19 at 06:26
  • Hi Stanley Can help to write the API, I'm using the C# code. – Eng Soon Cheah Dec 17 '19 at 06:27
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/204383/discussion-between-eng-soon-cheah-and-stanley-gong). – Eng Soon Cheah Dec 17 '19 at 06:28
  • Hi @EngSoonCheah , I have updated my answer , pls have a check – Stanley Gong Dec 17 '19 at 07:27
  • I got another question to ask is I'm retrieve the data from SharePoint on Premise , but the data did not shown ,show me the error. But I run at emulator , its shown me the data. – Eng Soon Cheah Dec 18 '19 at 01:31
  • Hi @EngSoonCheah, no problem, if this issue has been solved, pls mark my solution as an answer . For your other questions, pls post a new query, I'll take a look into it once I see it . Thanks! – Stanley Gong Dec 18 '19 at 01:43
  • https://stackoverflow.com/questions/59205348/chatbot-did-not-work-in-web-emulator-but-work-well-in-local-bot-framework-emulat – Eng Soon Cheah Dec 18 '19 at 01:47
1

You have to add the calling domain in the list of approved origins in the CORS menu of the app service running your csharpbotdw service.

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • Not understand. any sample? – Eng Soon Cheah Dec 13 '19 at 06:09
  • goto your csharpbotdw service and go to cors and add your bot endpoint (client) – Sajeetharan Dec 13 '19 at 06:17
  • I add http://localhost:63191 at CORS in Azure, but the chat bot does not shown anything: The error shown Failed to load resource: the server responded with a status of 404 (Not Found) [https://csharpbotdw.azurewebsites.net/directline/token] – Eng Soon Cheah Dec 13 '19 at 06:23
  • you need to have fiddler and see the request and response are working fine – Sajeetharan Dec 13 '19 at 06:39
  • The Reponse is Error "404Not Found" – Eng Soon Cheah Dec 13 '19 at 06:56
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/204171/discussion-between-eng-soon-cheah-and-sajeetharan). – Eng Soon Cheah Dec 13 '19 at 07:24
  • Make sure that CORS is enabled your Web API resource. See https://learn.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-rest-api#add-cors-functionality for steps on how to enable that. Note that said steps will only allow CORS from the localhost:5000. In a production environmen – Sajeetharan Dec 15 '19 at 10:23
  • Bro, Any example of ChatBot Sample Source code that Connect the SharePoint On Premise and the ChatBot not hosted inside the SharePoint? – Eng Soon Cheah Dec 16 '19 at 01:14
  • Can you refer to this GitHub [issue](https://github.com/Microsoft/BotFramework-WebChat/issues/1821) as the error is the same? – ranusharao Dec 16 '19 at 03:39
0

If the DirectLine or WebChat is created as "Bot Channel Registration" the below code will work.

(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')
         );
      })();