Как исправить проблему, связанную с ошибкой 500, возникающей в канале веб-чата, после нажатия кнопки «Отправить» в адаптивной карте в чат-боте, разработанной с помощью V4 C #?
Создание этой новой проблемы в соответствии с предложением @ mdrichardson-msft, поскольку проблема связана с конкретными / другими проблемами в приведенном ниже вопросе переполнения стека:
Есть ли способ включить опцию календаря в качестве входа в чат-бот V4 C #, кроме использования адаптивных карт?
На мой вопрос:
У меня есть класс диалогового окна «Водопад», в котором я использую карту Adaptive для выбора входов даты и времени и кнопку отправки на шаге 1, а затем на шаге № 2 значения регистрируются и обрабатываются после того, как я нажимаю на кнопку «Отправить» на шаге № 1.
В настоящее время, как указано в приведенной выше ссылке (проблема подробно описана ниже), я сталкиваюсь с ошибкой 500 в браузере при нажатии кнопки отправки на адаптивной карте:
ШАГ № 1:
Я показываю адаптивную карту с двумя входами даты и времени, один для запуска, а другой для остановки
Фактический результат:
Адаптив успешно отображается как в эмуляторе, так и в веб-чате без каких-либо проблем.
ШАГ # 2: Когда я нажимаю SetSchedule на адаптивной карте, отображаемой на шаге 1, значения должны быть записаны на шаге # 2 и отображаться на экране
Фактический результат:
Отлично работает в эмуляторе, но не в боте канала веб-чата. Я получаю сообщение об ошибке в веб-чате канала BOT. Пожалуйста, найдите HTML-файл для доступа к боту, класс диалога с водопадом и json-файл Adaptive card, прилагаемый для справки. Наряду с этим, пожалуйста, найдите скриншот ошибки, прикрепленный в канале веб-чата для справки. Я также проверил через TestinWebChat, и он тоже выдает ошибку.
Я опубликовал его через VSTS 2019 и не получил скриншот с ошибками, прикрепленный для ссылки "publishsuceeded_thruvisualStudio2019.jpg".
Не могли бы вы помочь мне решить эту проблему, как вы сделали для знака в проблеме? Запросите вашу немедленную помощь, это блокирует мою работу.
Язык: C #
SDK: V4
Опубликовано через: Visual Studio 2019
HTML:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Custom style options</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--
For demonstration purposes, we are using the development branch of Web Chat at "/master/webchat.js".
When you are using Web Chat for production, you should use the latest stable release at "/latest/webchat.js",
or lock down on a specific version with the following format: "/4.1.0/webchat.js".
-->
<script src="https://cdn.botframework.com/botframework-webchat/master/webchat.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 () {
// In this demo, we are using Direct Line token from MockBot.
// To talk to your bot, you should use the token exchanged using your Direct Line secret.
// You should never put the Direct Line secret in the browser or client app.
// https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication
// Token is found by going to Azure Portal > Your Web App Bot > Channels > Web Chat - Edit > Secret Keys - Show
// It looks something like this: pD*********xI.8ZbgTHof3GL_nM5***********aggt5qLOBrigZ8
const token = '<<Your Direct Line Secret Key>>';
// You can modify the style set by providing a limited set of style options
const styleOptions = {
botAvatarImage: 'https://docs.microsoft.com/en-us/azure/bot-service/v4sdk/media/logo_bot.svg?view=azure-bot-service-4.0',
botAvatarInitials: 'BF',
userAvatarImage: 'https://avatars1.githubusercontent.com/u/45868722?s=96&v=4',
userAvatarInitials: 'WC',
bubbleBackground: 'rgba(0, 0, 255, .1)',
bubbleFromUserBackground: 'rgba(0, 255, 0, .1)'
};
// We are using a customized store to add hooks to connect event
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
// When we receive DIRECT_LINE/CONNECT_FULFILLED action, we will send an event activity using WEB_CHAT/SEND_EVENT
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join',
value: { language: window.navigator.language }
}
});
}
return next(action);
});
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token }),
styleOptions,store
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html>
Код:
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace EchoBot.Dialogs
{
public class Adaptivecarddialog : WaterfallDialog
{
public const string cards = @"./AdaptiveCard.json";
public Adaptivecarddialog(string dialogId, IEnumerable<WaterfallStep> steps = null)
: base(dialogId, steps)
{
AddStep(async (stepContext, cancellationToken) =>
{
var cardAttachment = CreateAdaptiveCardAttachment(cards);
var reply = stepContext.Context.Activity.CreateReply();
reply.Attachments = new List<Attachment>() { cardAttachment };
await stepContext.Context.SendActivityAsync(reply, cancellationToken);
var opts = new PromptOptions
{
Prompt = new Activity
{
Type = ActivityTypes.Message,
// You can comment this out if you don't want to display any text. Still works.
}
};
// Display a Text Prompt and wait for input
return await stepContext.PromptAsync(nameof(TextPrompt), opts);
});
AddStep(async (stepContext, cancellationToken) =>
{
var res = stepContext.Result.ToString();
dynamic jobject = JsonConvert.DeserializeObject(res);
string NewStartDateTime = jobject.Startdate + " " + jobject.Starttime;
string NewStopDateTime = jobject.Stopdate + " " + jobject.Stoptime;
await stepContext.Context.SendActivityAsync($"StartDateTime:{NewStartDateTime}", cancellationToken: cancellationToken);
await stepContext.Context.SendActivityAsync($"StopDateTime:{NewStopDateTime}", cancellationToken: cancellationToken);
return await stepContext.EndDialogAsync();
});
}
public static new string Id => "Adaptivecarddialog";
public static Adaptivecarddialog Instance { get; } = new Adaptivecarddialog(Id);
public static Attachment CreateAdaptiveCardAttachment(string filePath)
{
var adaptiveCardJson = File.ReadAllText(filePath);
var adaptiveCardAttachment = new Attachment()
{
ContentType = "application/vnd.microsoft.card.adaptive",
Content = JsonConvert.DeserializeObject(adaptiveCardJson),
};
return adaptiveCardAttachment;
}
}
}
Адаптивная карта:
{
"type": "AdaptiveCard",
"body": [
{
"type": "TextBlock",
"id": "Start date text",
"separator": true,
"text": "Schedule Start DateTime:"
},
{
"type": "TextBlock",
"id": "DateTimeFormat",
"horizontalAlignment": "Center",
"separator": true,
"weight": "Bolder",
"color": "Warning",
"text": "(In UTC Time Zone)"
},
{
"type": "Input.Date",
"id": "Startdate",
"separator": true,
"value": "2019-05-24"
},
{
"type": "Input.Time",
"id": "Starttime",
"separator": true,
"value": "08:00"
},
{
"type": "TextBlock",
"id": "Stop date text",
"separator": true,
"text": "Schedule Stop DateTime:"
},
{
"type": "TextBlock",
"id": "DateTimeFormat",
"horizontalAlignment": "Center",
"separator": true,
"weight": "Bolder",
"color": "Warning",
"text": "(In UTC Time Zone)"
},
{
"type": "Input.Date",
"id": "Stopdate",
"separator": true,
"value": "2019-05-25"
},
{
"type": "Input.Time",
"id": "Stoptime",
"separator": true,
"value": "08:00"
}
],
"actions": [
{
"type": "Action.Submit",
"id": "SubmitBtn",
"title": "SetSchedule"
}
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.0"
}
Скриншоты:
Спасибо и всего наилучшего
-ChaitanyaNG
Дата: 6 июня-2019
Записать данные из KUDU для справки, руководствуясь Мэттом:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>IIS Detailed Error - 500.0 - Internal Server Error</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana,Arial,Helvetica,sans-serif;}
code{margin:0;color:#006600;font-size:1.1em;font-weight:bold;}
.config_source code{font-size:.8em;color:#000000;}
pre{margin:0;font-size:1.4em;word-wrap:break-word;}
ul,ol{margin:10px 0 10px 5px;}
ul.first,ol.first{margin-top:5px;}
fieldset{padding:0 15px 10px 15px;word-break:break-all;}
.summary-container fieldset{padding-bottom:5px;margin-top:4px;}
legend.no-expand-all{padding:2px 15px 4px 10px;margin:0 0 0 -12px;}
legend{color:#333333;;margin:4px 0 8px -12px;_margin-top:0px;
font-weight:bold;font-size:1em;}
a:link,a:visited{color:#007EFF;font-weight:bold;}
a:hover{text-decoration:none;}
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;}
h3{font-size:1.4em;margin:10px 0 0 0;color:#CC0000;}
h4{font-size:1.2em;margin:10px 0 5px 0;
}#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS",Verdana,sans-serif;
color:#FFF;background-color:#5C87B2;
}#content{margin:0 0 0 2%;position:relative;}
.summary-container,.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
.content-container p{margin:0 0 10px 0;
}#details-left{width:35%;float:left;margin-right:2%;
}#details-right{width:63%;float:left;overflow:hidden;
}#server_version{width:96%;_height:1px;min-height:1px;margin:0 0 5px 0;padding:11px 2% 8px 2%;color:#FFFFFF;
background-color:#5A7FA5;border-bottom:1px solid #C1CFDD;border-top:1px solid #4A6C8E;font-weight:normal;
font-size:1em;color:#FFF;text-align:right;
}#server_version p{margin:5px 0;}
table{margin:4px 0 4px 0;width:100%;border:none;}
td,th{vertical-align:top;padding:3px 0;text-align:left;font-weight:normal;border:none;}
th{width:30%;text-align:right;padding-right:2%;font-weight:bold;}
thead th{background-color:#ebebeb;width:25%;
}#details-right th{width:20%;}
table tr.alt td,table tr.alt th{}
.highlight-code{color:#CC0000;font-weight:bold;font-style:italic;}
.clear{clear:both;}
.preferred{padding:0 5px 2px 5px;font-weight:normal;background:#006633;color:#FFF;font-size:.8em;}
-->
</style>
</head>
<body>
<div id="content">
<div class="content-container">
<h3>HTTP Error 500.0 - Internal Server Error</h3>
<h4>The page cannot be displayed because an internal server error has occurred.</h4>
</div>
<div class="content-container">
<fieldset><h4>Most likely causes:</h4>
<ul> <li>IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred.</li> <li>IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly.</li> <li>IIS was not able to process configuration for the Web site or application.</li> <li>The authenticated user does not have permission to use this DLL.</li> <li>The request is mapped to a managed handler but the .NET Extensibility Feature is not installed.</li> </ul>
</fieldset>
</div>
<div class="content-container">
<fieldset><h4>Things you can try:</h4>
<ul> <li>Ensure that the NTFS permissions for the web.config file are correct and allow access to the Web server's machine account.</li> <li>Check the event logs to see if any additional information was logged.</li> <li>Verify the permissions for the DLL.</li> <li>Install the .NET Extensibility feature if the request is mapped to a managed handler.</li> <li>Create a tracing rule to track failed requests for this HTTP status code. For more information about creating a tracing rule for failed requests, click <a href="http://go.microsoft.com/fwlink/?LinkID=66439">here</a>. </li> </ul>
</fieldset>
</div>
<div class="content-container">
<fieldset><h4>Detailed Error Information:</h4>
<div id="details-left">
<table border="0" cellpadding="0" cellspacing="0">
<tr class="alt"><th>Module</th><td> AspNetCoreModule</td></tr>
<tr><th>Notification</th><td> ExecuteRequestHandler</td></tr>
<tr class="alt"><th>Handler</th><td> aspNetCore</td></tr>
<tr><th>Error Code</th><td> 0x00000000</td></tr>
</table>
</div>
<div id="details-right">
<table border="0" cellpadding="0" cellspacing="0">
<tr class="alt"><th>Requested URL</th><td> https://testbotforoauthprompt:80/api/messages</td></tr>
<tr><th>Physical Path</th><td> D:\home\site\wwwroot\api\messages</td></tr>
<tr class="alt"><th>Logon Method</th><td> Anonymous</td></tr>
<tr><th>Logon User</th><td> Anonymous</td></tr>
</table>
<div class="clear"></div>
</div>
</fieldset>
</div>
<div class="content-container">
<fieldset><h4>More Information:</h4>
This error means that there was a problem while processing the request. The request was received by the Web server, but during processing a fatal error occurred, causing the 500 error.
<p><a href="http://go.microsoft.com/fwlink/?LinkID=62293&IIS70Error=500,0,0x00000000,14393">View more information »</a></p>
<p>Microsoft Knowledge Base Articles:</p>
</fieldset>
</div>
</div>
</body>
</html>
2019-06-06 05:04:50 TESTBOTFOROAUTHPROMPT POST /api/messages X-ARR-LOG-ID=b3f7a170-d306-477e-b318-fbd82ec285f6 443 - 52.172.202.195 BF-DirectLine+(Microsoft-BotFramework/3.2++https://botframework.com/ua) ARRAffinity=232908322fb7729ed3fe519abf975a28a9506866f45a7a57c7acd29d79e24c2f - testbotforoauthprompt.azurewebsites.net 500 0 0 294 2493 3475
Пожалуйста, помогите мне решить эту проблему, и я прошу подробное пошаговое руководство, поскольку я очень новичок в коде и всех других технических вещах.
Если возможно, мы можем провести взаимно приемлемую сессию звонков скайпа / команд, чтобы мы могли пройти подробный пошаговый манер там, где это необходимо.
Дата: 16 июня 2019 г.
Обновление POST с дополнительными точками отладки.
Привет Мэтт,
Я отлаживал с помощью NGROK для удаленных каналов, таких как тестирование в веб-чате, а также эмулятор, чтобы увидеть, какие данные поступают по-другому:
Использование эмулятора:
При использовании эмулятора, когда я нажимаю кнопку внутри адаптивной карты, из эмулятора поступают данные канала, которые при анализе разбирают значение POSTBACK как истинное, в результате я могу перейти к следующему шагу в диалоговом окне с водопадом, благодаря которому добавлен дополнительный код для обработки данных с адаптивной карты было выполнено
Пожалуйста, смотрите скриншот с именем "ChannelDataComing_fromemulator.jpg" для справки.
Использование TestInWebChat из Azure:
Здесь данные канала поступают как NULL, из-за чего код выдает ошибку, так как он не может его проанализировать, так как нет анализа, он выдает ошибку как ссылку на объект.Нет данных канала, нет POSTback, поэтому он не переходит к следующему шагу водопада для обработки данных.
Пожалуйста, смотрите скриншот с именем "ChannelDataComingnull_fromTestinWeBChat.jpg" для справки.
Запросы :
- Почему данные канала не поступают при прохождении теста, выполненного в эмуляторе?
- Как получить данные канала для передачи в этом случаетак что POST возвращается как истина, и тогда будет выполнен следующий шаг водопада?
- Если это не работает, есть ли другой способ сделать это, чтобы перейти к следующему шагу, и я могу обработатьданные, которые мне кажутся подходящими?
Не замечено, что данные канала поступают, когда отправляется первое сообщение HI, поскольку код находится внутри условия Activity == Message и каналане имеет обратной отправки, код не выполняется полностью, но после нажатия кнопки «Отправить» в адаптивной карте после отображения данных каналаа не приходит не знаю почему?
Пожалуйста, помогите мне решить эту проблему, так как я застрял здесь, и я действительно хочу, чтобы это работало?