ASP.NET MVC Webhookプロジェクトの作成
Webhooks - URLs you expose to handle callbacks - are pivotal to harnessing the power of Twilio in your web application. A powerful concept, webhooks also happen to be very easy to create in your ASP.NET MVC Project. We'll prove it - let's expose some webhooks in ASP.NET MVC and receive some text messages!
Twilio can send your web application an HTTP request when certain events happen, such as an incoming text message to one of your Twilio phone numbers. These requests are called webhooks, or status callbacks. For more, check out our guide to Getting Started with Twilio Webhooks. Find other webhook pages, such as a security guide and an FAQ in the Webhooks section of the docs.
Webhooks and ASP.NET MVC Projects
For one webhook example, when receiving an SMS (text) message, Twilio will call your application with data describing the incoming message. The same process applies for Programmable Voice, Programmable Chat, Programmable Video, and the other Twilio APIs.
This guide will walk you through setting up a basic project for handling incoming webhook requests in your project. The screenshots in the steps shown were made with Visual Studio 2015, but the process is much the same in Visual Studio 2013 and 2017.
Create the Project
Create a new ASP.NET MVC project that can handle incoming requests from Twilio. Open up Visual Studio and select File... New Project. Find the ASP.NET Web Application template for C# as shown here:
目的に合わせて、プロジェクトとソリューションに名前をつけます。
OKをクリックすると、ASP.NETプロジェクトの詳細について入力を求められます。
An "Empty" project is all you need if you will only be handling webhook requests, but be sure to select the MVC option for adding folders and core references. Finally, select “Host in the cloud” if you want to be able to easily publish your app to Azure. Twilio will need a publicly reachable URL to which to send requests and hosting in Azure fits this bill.
Azureでホストする
Azureにホストする選択肢を選んだ場合、「Azure Web アプリケーション設定」ダイアログが表示されます。
この時点で、Microsoft Azureサブスクリプションにログインする必要があります。 ログインが完了したら、グローバルに一意なWebアプリケーション名(一意な名前が選択されると、緑色のチェックマークが表示されます)を入力する必要があります。 この名前は後々、Webhook用のURLの一部として使用しますので、控えておくようにしてください。
You will likely need to create a new App Service plan and Resource group, unless you’ve already been deploying your own Web Apps to Azure. You can select whatever Region you like and a Database server based on whether you will need one for your app. If you will just be calling other API's, then you likely do not need one.
OKをクリックしたら、Visual Studioは新規プロジェクトを作成し、Azure上にアプリケーションを発行します。 Visual Studio内の「Azure App Service のアクティビティ」を確認することで、発行が完了しているかどうかを確認できます。
NuGet パッケージ
プロジェクトの下準備を終えるため、NuGetパッケージ・マネージャーでいくつかの依存関係をインストールする必要があります。 「ツール」→「NuGet Package Manager」→「Package Manager コンソール」メニューからアクセスできるコンソールを使用すれば、この作業はほんの一瞬で完了します。
To get the Twilio helper libraries you will need use the following command. It requests the Twilio.AspNet.Mvc package, telling NuGet to get the latest versions of the dependent Twilio package:
Install-Package Twilio.AspNet.Mvc -DependencyVersion HighestMinor
「Hello World」コントローラーを作成する
To explore how to handle webhooks in ASP.NET MVC, this guide will use the Twilio Programmable SMS product. When Twilio receives an SMS message at a phone number that you own it will call your webhook. We can listen for this webhook using an ASP.NET MVC Controller.
「ソリューションエクスプローラー」内のプロジェクトの [Controllers] フォルダーを見つけます:
Right-click the folder and select Add... Controller... Choose an empty MVC 5 Controller:
用途に適した名前をコントローラーに付けます:
using
ステートメントを更新して、Twilio名前空間をインポートします:
using Twilio.AspNet.Common; using Twilio.AspNet.Mvc; using Twilio.TwiML;
続いてコントーローラーのクラスについて、ASP.NET MVCによって提供される既定の Controller
に代わって、 TwilioController
から継承されるように変更します:
public class HelloWorldController : TwilioController
続いて、Index
アクションメソッドを[HttpPost]
属性を、TwiMLResult
およびSmsRequest
パラメーターの戻り値を持つよう変更します。
[HttpPost] public TwiMLResult Index(SmsRequest request)
SmsRequest
クラスは Twilio.AspNet.Mvc
ライブラリー内で定義され、すべてのデシリアライズされたTwilioが渡すパラメーターが含まれています。音声通話に応答したら、 VoiceRequest
クラスを使用します。
Twilio expects your webhook to return TwiML (XML), but you don’t need to code the XML by hand. You can make use of the MessagingResponse
and VoiceResponse
classes (from the Twilio
library) to build a TwiML response programmatically. These classes contain methods corresponding to the TwiML verbs that Twilio understands.
下記のように、アクション・メソッドを更新します:
"Hello World" メッセージを追加後、 TwilioController
によって提供される TwiML
関数を呼び出します。 これは通常のASP.NET MVCコントローラー・アクション内で View(myModel)
を呼び出すことに似ています。
ローカル環境でテストおよびデバッグする
Visual Studio内からアプリケーションを実行し、ブラウザーでアプリケーションを表示させます。 現状では、アプリケーション用の既定のホームページがありません。
You might think to add /HelloWorld
(or whatever you named your controller) to the URL in the browser. You would be on the right track, but this will still return a 404
because your browser will be doing a GET
request instead of a POST
request. You can break out a tool like Fiddler or Postman to test POST requests to your newly created controller, but there is a simpler way that’s built right into Windows - PowerShell. Open a new PowerShell window and run the following command:
Invoke-WebRequest http://localhost:XXXXX/HelloWorld -Method POST
XXXXX をVisual StudioがWebアプリケーションに割り当てたランダムなポート番号に置き換えます。 このポート番号は、最初にアプリケーションをブラウザーで開いた際のURLで確認できます。 HelloWorld を、コントローラーに付けた名前(末尾のController
部分を除く)に変更します。
これによって、コントローラーからのレスポンスを伴ったPowerShellオブジェクトが返されます。
StatusCode : 200 StatusDescription : OK Content : <?xml version="1.0" encoding="utf-8"?> <Response> <Message>Hello World</Message> </Response> RawContent : ...
Content
プロパティーで返された生のXMLオブジェクトがご覧いただけるはずです。上級テクニック: ひとつのコマンドだけで Content
プロパティーを確認できます。
(Invoke-WebRequest http://localhost:XXXXX/HelloWorld -Method POST).Content
(Want more detailed information on using PowerShell with HTTP Requests or Twilio? Try our guide to sending HTTP Requests with PowerShell).
ASP.NET MVCアプリケーションをデプロイおよびテストする
Azureへ発行する
アプリケーションをAzureに発行するには、Visual Studio内で「Azure App Service のアクティビティ」を見つけて、「発行」ボタンをクリックします。
発行が完了すれば、再度PowerShellからアプリケーションをテストできます:
Invoke-WebRequest https://yourapp.azurewebsites.net/HelloWorld -Method POST
yourapp
をAzureのWebアプリケーション用に選択した名前に、そして HelloWorld
をコントローラーの名前に置き換えます。
ここまで問題なく完了した前提で、Twilio内で電話番号にWebhookを紐付ける手順に進むことにします。 (デプロイせずにWebhookをローカルでデバッグする方法を学ぶには、該当トピックのガイドを参照してください。
電話番号を構成する
Twilioの電話番号をまだご購入いただいていない場合、こちらで購入しておいてください。 それが済んだら、下記のようにメッセージングWebhookを構成できます。
先にPowerShellでテストした、同じAzure WebアプリケーションのURLを使用します。 「保存」ボタンをクリックして、構成が電話番号に保存されていることを確認してください。
お疲れさま! SMSメッセージをこの電話番号宛に送信すれば、"Hello World" という返信が送られてくるはずです。
終わりに
This walkthrough should get you most of the way down the path to handling webhooks in ASP.NET MVC projects. For more in-depth examples, see the complete applications for a variety of Twilio use cases that are documented in our Tutorials.
ヘルプが必要ですか?
誰しもが一度は考える「コーディングって難しい」。そんな時は、お問い合わせフォームから質問してください。 または、Stack Overflow でTwilioタグのついた情報から欲しいものを探してみましょう。