如何在ASP.NET MVC中创建webhook?

时间:2014-10-17 03:10:06

标签: c# asp.net-mvc callback http-post webhooks

我正在尝试创建一个简单的webhook来接收来自Nexmo SMS服务的送货回执。他们网站上唯一的文件就是这个。

During account set-up, you will be asked to supply Nexmo a CallBack URL for Delivery Receipt to which we will send a delivery receipt for each of your SMS submissions. This will confirm whether your message reached the recipient's handset. The request parameters are sent via a GET (default) to your Callback URL and Nexmo will be expecting response 200 OK response, or it will keep retrying until the Delivery Receipt expires (up to 72 hours).

我一直在寻找这样做的方法,到目前为止,我从网上找到的一个例子中得到了这个方法,虽然我不确定这是否正确。无论如何,这是在ASP.NET和端口6563上运行,所以这是我应该听的端口吗?我下载了一个名为ngrok的应用程序,它应该将我的本地Web服务器暴露给互联网,所以我运行了应用程序并指示它监听端口6563,但没有运气。我一直在试图找到一些帖子来发布这个功能。

[HttpPost]
public ActionResult CallbackURL()
{
    System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Request.InputStream);
    string rawSendGridJSON = reader.ReadToEnd();
    return new HttpStatusCodeResult(200);
}

通常我只需访问http://localhost:6563/Home/Index/CallbackURL即可直接调用该函数返回视图 所以我在方法签名上插入了一个断点,但是只有从它中删除[HttpPost]才会被调用。我应该尝试的任何后续步骤?

4 个答案:

答案 0 :(得分:3)

首先,您必须删除[HttpPost]位,因为它清楚地表明"参数是通过GET"发送的。

然后您还应该删除返回HttpStatusCodeResult(200),因为如果没有错误发生,它将返回200 OK状态代码。

然后你应该简单地从querystring或使用模型绑定读取值。这是一个示例:

    public string CallbackURL()
    {
        string vals = "";

        // get all the sent data 
        foreach (String key in Request.QueryString.AllKeys)
            vals += key + ": " + Request.QueryString[key] + Environment.NewLine;

        // send all received data to email or use other logging mechanism
        // make sure you have the host correctly setup in web.config
        SmtpClient smptClient = new SmtpClient();
        MailMessage mailMessage = new MailMessage();
        mailMessage.To.Add("...@...com");
        mailMessage.From = new MailAddress("..@....com");
        mailMessage.Subject = "callback received";
        mailMessage.Body = "Received data: " + Environment.NewLine + vals;
        mailMessage.IsBodyHtml = false;
        smptClient.Send(mailMessage);

        // TODO: process data (save to database?)

        // disaplay the data (for degugging purposes only - to be removed)
        return vals.Replace(Environment.NewLine, "<br />");
    }

答案 1 :(得分:2)

几周之前,Asp.Net团队宣布支持使用Visual Studio进行Web Hooks。

请点击此处查看更多详细信息:

https://neelbhatt40.wordpress.com/2015/10/14/webhooks-in-asp-net-a-visual-studio-extension/

答案 2 :(得分:1)

Microsoft正在开发ASP.NET WebHooks,这是ASP.NET系列的新成员。它支持轻量级HTTP模式,提供简单的发布/订阅模型,用于将Web API和SaaS服务连接在一起。

请参阅Introducing Microsoft ASP.NET WebHooks Preview

答案 3 :(得分:0)

所以我遇到的问题根本不在于我的webhook,实际上是IIS Express。显然它阻止了来自外部主机的大部分流量,因此在将任何内容隧道传输到服务器之前,您可以进行一些调整。如果您遵循这些指南,您应该有一个正常工作的服务器。

https://gist.github.com/nsbingham/9548754

https://www.twilio.com/blog/2014/03/configure-windows-for-local-webhook-testing-using-ngrok.html

相关问题