How do you turn a handful of isolated messages to and from the same party into a true conversation? You need some way to remember state between each message that is exchanged. This is because SMS is a stateless protocol. Building traditional web applications has this same hurdle, as HTTP is also a stateless protocol. This problem has been solved for web applications through the use of HTTP cookies and, rather than reinvent the wheel, the Twilio Messaging API uses the same solution.
This guide will show you how to use Programmable Messaging to accomplish this in your ASP.NET application. The code snippets in this guide are written using modern C# language features and require the .NET Framework version 4.5 or higher. They also make use of the Twilio C# SDK.
If you haven't written your own SMS webhooks with C# and ASP.NET before, you may want to first check out our guide, Receive and Reply to SMS and MMS Messages in C#. Ready to go? Let's get started!
Twilio Conversations, a more recent product offering, is an omni-channel messaging platform that allows you to build engaging conversational, two-way messaging experiences. Be sure to check out our Conversations product to see if it's a better fit for your needs.
The cookies let you share state across multiple messages allowing you to treat separate messages as a conversation, and store data about the conversation in the cookies for future reference.
You can store the data directly in a cookie, or you can use a session state management framework. The code sample below does the latter, using the Session State feature available in ASP.NET.
Let's try using session counters to see if a particular user has messaged us before. If they're a new sender, we'll thank them for the new message. If they've sent us messages before, we'll specify how many messages we've gotten from them.
1// In Package Manager, run:2// Install-Package Twilio.AspNet.Mvc -DependencyVersion HighestMinor34using System.Collections.Generic;5using System.Web.Mvc;6using Twilio.AspNet.Mvc;7using Twilio.TwiML;89public class SmsController : TwilioController10{11[HttpPost]12public ActionResult Index()13{14var counter = 0;1516// get the session varible if it exists17if (Session["counter"] != null)18{19counter = (int) Session["counter"];20}2122// increment it23counter++;2425// save it26Session["counter"] = counter;2728// make an associative array of senders we know, indexed by phone number29var people = new Dictionary<string, string>()30{31{"+14158675308", "Rey"},32{"+12349013030", "Finn"},33{"+12348134522", "Chewy"}34};3536// if the sender is known, then greet them by name37var name = "Friend";38var from = Request.Form["From"];39var to = Request.Form["To"];40if (people.ContainsKey(from))41{42name = people[from];43}4445var response = new MessagingResponse();46response.Message($"{name} has messaged {to} {counter} times");4748return TwiML(response);49}50}