【发布时间】:2017-12-26 15:39:54
【问题描述】:
我想使用 Microsoft Bot Builder 创建一个机器人,它将接收到的消息发送到 webhook 端点。我尝试结合一些从搜索中找到的示例,但无济于事。我需要一些帮助才能将用户输入文本作为带有文本值的 json 有效负载发送到 webhook,这是我现在拥有的代码:
using System;
using System.Net;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using System.Web.Script.Serialization;
namespace Bot_Application1.Dialogs
{
[Serializable]
public class RootDialog : IDialog<object>
{
public Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
return Task.CompletedTask;
}
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var activity = await result as Activity;
// calculate something for us to return
int length = (activity.Text ?? string.Empty).Length;
// return our reply to the user
await context.PostAsync($"You sent {activity.Text} which was {length} characters");
//
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://outlook.office.com/webhook/.../IncomingWebhook/.../...");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
text = "\"" + activity.Text + "\""
});
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
//
context.Wait(MessageReceivedAsync);
}
}
}
这是基于https://docs.microsoft.com/en-us/bot-framework/dotnet/bot-builder-dotnet-quickstart
当我在使用 Fiddler 进行监控时对此进行测试时,我可以看到机器人和客户端之间的通信,但看不到任何 REST http 请求。我不确定这是否是最好的方法,并且希望得到一些反馈。
到此端点的成功 POST 如下所示:
POST /webhook/.../IncomingWebhook/.../... HTTP/1.1
Host: outlook.office.com
User-Agent: insomnia/5.12.4
Content-Type: application/json
Accept: application/json
Content-Length: 26
{
"text":"Hello world!"
}
感谢您的帮助!
【问题讨论】:
-
您正在形成请求,但最后没有发出请求。缺少代码
(HttpWebResponse)httpWebRequest.GetResponse();。看看下面的答案。
标签: c# json rest bots botframework