Creating an ASP.NET MVC Webhook Project

David Prothero David Prothero

Webhooks are pivotal to harnessing the power of Twilio. For example, when receiving a SMS (text) message on your Twilio phone number Twillio will call your application with data describing the incoming message. The same thing can happen for Programmable Voice, IP Messaging, Programmable Video, and the other Twilio API's.

This guide will walk you through setting up a basic project for handling incoming webhook requests. The screenshots in the steps shown were made with Visual Studio 2015, but the process is much the same in Visual Studio 2013.

Creating 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:

Visual Studio - New ASP.NET Web Application

Name the project and solution to suit your needs.

After clicking OK, you will be prompted for the ASP.NET Project details:

Visual Studio - New ASP.NET Project

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.

Hosting in Azure

If you select the option to host in Azure, the next dialog to pop up will be the Azure Web App Settings:

Visual Studio - Configure Azure Web App

At this point you will need to login to your Microsoft Azure subscription. Once you’re logged in, you must enter a Web App name that will be globally unique (you will get a green checkmark once you’ve selected a unique name). Keep track of that name for later, as it will be part of the URL for your webhook.

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.

Once you click OK, Visual Studio will create your new project and publish your app to Azure. You will know it is complete by looking at the "Azure App Service Activity" tab in Visual Studio:

Visual Studio - Azure App Service Activity

NuGet Packages

To finish off the framing of the project, you need to install a few dependencies via the NuGet Package Manager. This can be most quickly accomplished using the Console, which you can reach by choosing the Tools menu, NuGet Package Manager, and Package Manager Console.

To get the Twilio helper libraries you will need use the following command. It requests the Twilio.Mvc package, telling NuGet to get the latest versions of the dependent Twilio packages (Twilio and Twilio.TwiML):

Install-Package Twilio.Mvc -DependencyVersion HighestMinor

Creating a Hello World Controller

To explore how to handle webhooks in ASP.NET MVC, this guide will use the Twilio Programmable SMS product. When Twilio receives a 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.

Find the “Controllers” folder of your new project in the Solution Explorer:

Visual Studio - Solution Explorer - Controllers

Right-click the folder and select Add… Controller… Choose an empty MVC 5 Controller:

Visual Studio - MVC 5 Empty Controller

Name the controller whatever makes sense for your use case:

Visual Studio - Name Controller

Update your using statements to import the Twilio namespaces:

using Twilio.Mvc;
using Twilio.TwiML;
using Twilio.TwiML.Mvc;

Then, change your controller class to inherit from TwilioController instead of the default Controller provided by ASP.NET MVC:

public class HelloWorldController : TwilioController

Next, modify the Index action method to have the [HttpPost] attribute, a return value of TwiMLResult and an SmsRequest parameter:

[HttpPost]
public TwiMLResult Index(SmsRequest request)

The SmsRequest class is defined in the Twilio.Mvc library and will contain all of the deserialized parameters that Twilio will pass to us. If you were responding to a voice call, then you would use the VoiceRequest class.

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 TwilioResponse class (from Twilio.TwiML) to build a TwiML response programmatically. This class contains methods corresponding to the TwiML verbs that Twilio understands.

Update your action method as follows:

using System.Web.Mvc;
using Twilio.Mvc;
using Twilio.TwiML;
using Twilio.TwiML.Mvc;

namespace WebApplication18.Controllers
{
    public class SmsController : TwilioController
    {
        [HttpPost]
        public TwiMLResult Index(SmsRequest request)
        {
            var response = new TwilioResponse();
            response.Message("Hello World");
            return TwiML(response);
        }
    }
}
ASP.NET MVC Webhook Example

Example ASP.NET MVC Action that responds to a Twilio SMS webhook.

After adding the “Hello World” message, call the TwiML function provided by TwilioController. This is analogous to calling View(myModel) in a typical ASP.NET MVC controller action.

Testing and Debugging Locally

Run your application from within Visual Studio to view your application in the browser. In this case, there isn't a default home page for your app:

Visual Studio - 404 Error for Root

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

Replace the XXXXX with the random port number that Visual Studio assigned to your web app. You can find this in the URL when Visual Studio first launched your app in the browser. Change HelloWorld to whatever you named your controller (without the Controller suffix).

This will return a PowerShell object with the response from your controller:

StatusCode        : 200
StatusDescription : OK
Content           : <?xml version="1.0" encoding="utf-8"?>
                    <Response>
                      <Message>Hello World</Message>
                    </Response>
RawContent        : ...

You should be able to see the raw XML response we are returning in the Content property. Pro-tip: you can see just the Content property with a single command:

(Invoke-WebRequest http://localhost:XXXXX/HelloWorld -Method POST).Content

Deploying and Testing the App

Publish to Azure

To publish your app to Azure, find the “Azure App Service Activity” tab in Visual Studio and click the Publish button:

Visual Studio - Azure Publish

Once the publish is complete, you can test your app from PowerShell again:

Invoke-WebRequest https://yourapp.azurewebsites.net/HelloWorld -Method POST

Replace yourapp with the name you selected for your Azure Web App and HelloWorld with the name of your controller.

Assuming that works, you can move on to attaching your webhook to a phone number in Twilio. (To learn how to debug your webhook locally without deploying, see our guide on that topic.)

Configure a Twilio Number

If you haven’t already purchased a Twilio phone number, do so now. Once that is done, you can configure the Messaging Webhook like so:

Twilio Messaging Webhook - Azure

Use the same URL for your Azure Web App that you tested in PowerShell earlier. Be sure to click the SAVE button to save your configuration for the phone number.

Test it out! Send any text message to your number and you should get back the ‘Hello World’ response:

SMS Sample - Hello World

Conclusion

This should get you started down the path to handling webhooks in ASP.NET MVC. For more in-depth examples, see the complete applications for a variety of use cases that are documented in our Tutorials.

David Prothero
1 / 1
Loading Code Samples...
using System.Web.Mvc;
using Twilio.Mvc;
using Twilio.TwiML;
using Twilio.TwiML.Mvc;

namespace WebApplication18.Controllers
{
    public class SmsController : TwilioController
    {
        [HttpPost]
        public TwiMLResult Index(SmsRequest request)
        {
            var response = new TwilioResponse();
            response.Message("Hello World");
            return TwiML(response);
        }
    }
}