Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a REST API to receive an SMS via Twilio Number Using ASp.net Web Api

I am new to Web Api/Rest API concept but I plan to use Visual Studio 2012 MVC4 Web Api. How the heck do I create an application to receive a Text/SMS Message via Twilio and send the response back? I have searched several articles here and at Twilio website but none of them give me any insight on how to use MVC4 Web Api. Can somebody please help me and show/give some examples?

like image 311
Ditty Avatar asked Dec 09 '22 14:12

Ditty


2 Answers

I really don't like any of the documentation out there I found pertaining to Web API, so I wanted to answer this question even though it is a tad stale.

Twilio will issue an HTTP request (you can choose GET or POST verb on Twilio site) to an endpoint that you create and your HTTP response, if the body is formed properly, will issue an SMS response back to the user. I show the Twilio configuration screen shot at the bottom here.

I normally only return json from my endpoints, but for Twilio you must return XML. Set up your routing to have an extension mapped routing (this allows you to set up a URL that will return XML for the Twilio request). This is necessary because Twilio doesn't post text/xml in the Accept header. They actually do have an Accept header, but it contains */* but will fail with anything except XML:

        config.Routes.MapHttpRoute(
            name: "DefaultApiWithExtension",
            routeTemplate: "xml/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional, ext="xml" }
        );

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{id}",
            defaults: new { id = RouteParameter.Optional}
        );

        config.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "application/xml");
        config.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");

Now install the TwiML nuget package using the package manager console. This will be used for the TwilioResponse class only.

Install-Package Twilio.TwiML

Add this class if you want to, not required though if you just want to put the params in the controller action method.

public class TwilioRequest
{
    public string MessageSid { get; set; }
    public string AccountSid { get; set; }
    public string From { get; set; }
    public string To { get; set; }
    public string Body { get; set; }
}

And then your controller action is something like this:

    public virtual HttpResponseMessage Get([FromUri]TwilioRequest request)
    {            
        TwilioResponse tr = new TwilioResponse();

        if (request.Body == "Hello World")
            tr.Message("Hello back!");
        else
            tr.Message("Text 'Hello World' for a friendly message.");

        return Request.CreateResponse(HttpStatusCode.OK, tr.Element);
    }

or this if you don't want to use the TwilioRequest class that I made:

    public virtual HttpResponseMessage Get(string body)
    {            
        TwilioResponse tr = new TwilioResponse();

        if (body == "Hello World")
            tr.Message("Hello back!");
        else
            tr.Message("Text 'Hello World' for a friendly message.");

        return Request.CreateResponse(HttpStatusCode.OK, tr.Element);
    }

Finally to test it you will need to configure Twilio to do a GET request to your endpoint. This is what that looked like on their site at the time of this posting:

enter image description here

Notice that the configuration URL has the /xml/controllername pattern in it. You can test this in the browser, postman, or fiddler before hitting it with Twilio though. The response body should look something like this if working correctly:

<response>
<message>Hello Back!</message>
</response>

Final notes:

Technically you don't even need the TwiML library as it only provides a wrapper class that serializes to XML and you could write your own in a couple minutes. Also I found it useful to open up a port on the firewall that sent http requests from Twilio to my machine directly so that I could debug when Twilio was working properly.

like image 148
Quesi Avatar answered Dec 11 '22 03:12

Quesi


Twilio evangelist here.

All of our Quickstarts are translated to C# that uses the Razor syntax. You just need to select C# from the language drop down at the top of the page. Here is a direct link to the start of the C# SMS quickstarts:

http://www.twilio.com/docs/quickstart/csharp/sms

Also, you might want to check out a series of blog posts I wrote a while ago introducing Twilio to .NET developers, including one on using the Twilio .NET helper library in an ASP.NET MVC application:

Specifically for info on responding to text message you'll probably be most interested in Parts 1,2,4 & 7.

Lastly, if you hit the Twilio .NET helper library wiki on GitHub there are some code samples there:

https://github.com/twilio/twilio-csharp/wiki

I'll also point you at a blog post that developer Long Le wrote for our blog that shows how to reply to Twilio requests using ASp.NET Web API since there are a couple of details needed to do that:

http://www.twilio.com/blog/2012/11/building-twilio-apps-using-asp-net-mvc-4-web-api.html

Personally I find it easier just to use a standard ASP.NET MVC Controller, but thats just my personal preference.

Hope that helps.

like image 27
Devin Rader Avatar answered Dec 11 '22 04:12

Devin Rader