簡體   English   中英

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

[英]How do I create a webhook in ASP.NET MVC?

我正在嘗試創建一個簡單的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]來自它。 我應該嘗試的任何后續步驟?

首先,您必須刪除[HttpPost]位,因為它清楚地表明“參數是通過GET發送的”。

然后你還應該刪除返回HttpStatusCodeResult(200),因為如果沒有錯誤發生,它將返回200 OK狀態代碼。

然后,您應該只是從查詢字符串或使用模型綁定讀取值。 這是一個示例:

    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 />");
    }

幾周之前,Asp.Net團隊宣布支持使用Visual Studio的Web Hooks。

請查看更多詳細信息:

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

Microsoft正在開發ASP.NET WebHooks,這是ASP.NET系列的新成員。 它支持輕量級HTTP模式,提供簡單的發布/訂閱模型,用於將Web API和SaaS服務連接在一起。

請參閱Microsoft ASP.NET WebHooks預覽簡介

所以我遇到的問題根本不在於我的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM