2014-10-17 85 views
6

我正在嘗試創建一個簡單的webhook來接收Nexmo SMS服務的收貨收據。他們網站上唯一的文檔是這樣的。如何在ASP.NET MVC中創建webhook?

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]從它。我應該嘗試下一步嗎?

+0

請看看這裏的更多詳細信息: https://neelbhatt40.wordpress.com/2015/10/14/ webhooks-in-asp-net-a-visual-studio-extension/ – Neel 2015-10-16 05:09:13

回答

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("[email protected]"); 
     mailMessage.From = new MailAddress("[email protected]"); 
     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 />"); 
    } 
+0

現在的問題實際上是能夠接收來自網絡的請求。所以,說我在我的本地機器上運行我的服務器,我想調用我的CallbackURL函數,然後我可以直接將我的Web瀏覽器指向localhost:6563/Home/CallbackURL。但正如我所說,我需要它可以公開訪問,所以我使用ngrok作爲請求之間的中介。這是我現在遇到問題的地方,所以ngrok應該轉發到服務器正在運行的端口6563。但是,當我可以我的http://domain.ngrok.com/Home/CallbackURL時,我得到一個400錯誤的請求。 – 2014-10-19 16:43:33

+0

我想爲易趣肥皂通知創建訂閱者和接收者。我想使用webhook。我可以在同一個應用程序中嗎? – coder771 2017-05-05 13:06:57