У меня есть веб-приложение Azure с приложением ASP.NET REST API, которое работает как служба для регистрации каналов ботов.
В этом приложении у меня есть одна конечная точка
public async Task<IHttpActionResult> Post(string userToken, string botName, [FromBody] Activity activity)
, где я получаю сообщение от пользователя, обрабатываю его и отправляю обратно.
Когда я пытаюсь связаться обратнопользователю (либо с вводом текста, либо с фактическим ответом)
private static async Task ShowTyping(Activity activity, ConnectorClient client)
{
var typingResponse = new Activity
{
Conversation = activity.Conversation,
From = activity.Recipient,
Locale = activity.Locale,
Recipient = activity.From,
ReplyToId = activity.Id,
Id = activity.Id,
Type = "typing"
};
await client.Conversations.UpdateActivityAsync(typingResponse);
}
...
foreach (var reply in replies)
{
Trace.TraceInformation($"[{userToken}:{botName}] Sending reply {reply.Id}:{reply.Text}");
await client.Conversations.ReplyToActivityAsync(reply);
}
через REST API я получаю HttpRequestException - An existing connection was forcibly closed by the remote host
:
2019-01-22T15:49:54 PID[17864] Error System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult) at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
--- End of inner exception stack trace --- at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult) at System.Net.PooledStream.EndWrite(IAsyncResult asyncResult) at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar) --- End of inner exception stack trace --- at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context) at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar) --- End of inner exception stack trace --- at Microsoft.Rest.RetryDelegatingHandler.<SendAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) at Microsoft.Bot.Connector.Conversations.<UpdateActivityWithHttpMessagesAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Connector.ConversationsExtensions.<UpdateActivityAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at ChatFirst.Channels.BotFramework.Controllers.WebhookController.<ShowTyping>d__5.MoveNext()
Все отлично работает на эмуляторе и совсем не работает в веб-сервисе.Я пытался реализовать клиент REST API самостоятельно, но получил тот же результат.
Чего мне не хватает?
Больше информации по проблеме
Я использую v4.2 пакеты Bot Framework
<package id="Microsoft.Bot.Builder" version="4.2.0" targetFramework="net472" />
<package id="Microsoft.Bot.Connector" version="4.2.0" targetFramework="net472" />
<package id="Microsoft.Bot.Schema" version="4.2.0" targetFramework="net472" />
Весь метод Post, userToken
и botName
моивнутренние учетные данные
/// <summary>
/// POST: api/v1/webhook/{userToken}/{botName}
/// Receive a message from a user and reply to it
/// </summary>
[HttpPost]
[Route("api/v1/webhook/{userToken}/{botName}")]
public async Task<IHttpActionResult> Post(string userToken, string botName, [FromBody] Activity activity)
{
try
{
if (activity.Type == ActivityTypes.Message)
{
Trace.TraceInformation($"[{userToken}:{botName}] Message from {activity.From.Id}");
MicrosoftAppCredentials credentials = _channelGateway.GetCredentials(userToken, botName);
if (credentials == null)
return Ok();
var serviceUri = new Uri(activity.ServiceUrl);
var client = new ConnectorClient(serviceUri, credentials);
await ShowTyping(activity, client);
IEnumerable<Activity> replies = await _coreTalkService.GetRepliesAsync(new BotToken(userToken, botName), activity);
foreach (var reply in replies)
{
Trace.TraceInformation($"[{userToken}:{botName}] Sending reply {reply.Id}:{reply.Text}");
await client.Conversations.ReplyToActivityAsync(reply);
}
}
else
{
HandleSystemMessage(activity);
}
return Ok();
}
catch (Exception e)
{
Trace.TraceError(e.ToString());
return InternalServerError(e);
}
}
Настройки регистрации каналов Bot выглядят следующим образом
Если я перенаправлю канал Botв локальный экземпляр на моем ПК разработчика через ngrok я получаю те же ошибки.
Я сократил весь метод для выполнения простого эхо-ответа, но ошибка все еще остается
public async Task<IHttpActionResult> Post(string userToken, string botName, [FromBody] Activity activity)
{
Trace.TraceInformation($"[{userToken}:{botName}] Message from {activity.From.Id}");
var client = new ConnectorClient(new Uri(activity.ServiceUrl),
new MicrosoftAppCredentials("<secret>", "<secret>"));
var answer = activity.CreateReply(activity.Text, activity.Locale);
await client.Conversations.ReplyToActivityAsync(answer);
return Ok();
}
activity.ServiceUrl
is
https://webchat.botframework.com/
Ошибка возникает, если сообщение отправлено через веб-чат, я не проверял другие каналы