Create an SMS Conversation in C#

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 Programmable SMS makes this easy for you and 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!

Using HTTP Cookies with Webhooks

Just like in web applications, a cookie is a small file that your application can store on Twilio's servers to keep track of information, such as a username or account. For Twilio SMS, cookies are scoped to the "conversation" between two parties -- you can have a unique cookie for each To/From phone number pair. For example, you can store a unique cookie for any messages sent between 415-555-2222 and 415-555-1111, which will be different than the cookie used between 415-555-3333 and 415-555-1111.

Why cookies?

In web apps, you write a cookie to keep "statefulness" between separate requests from the same browser. Similarly, SMS messages are independent communications between two parties, so Twilio allows you to tie them together as a logical session via cookies. This means you can use server-side sessions to keep track of application state between requests. How cool is that? Twilio will expire the cookies for that conversation after four hours of inactivity, as if the user "closed the browser."

Storing Conversation Data

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.

Track SMS Conversations using a Session

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.

Loading Code Samples...
Language
SDK Version:
  • 4.x
  • 5.x
// In Package Manager, run:
// Install-Package Twilio.Mvc -DependencyVersion HighestMinor

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

public class SmsController : TwilioController
{
    [HttpPost]
    public ActionResult Index(SmsRequest request)
    {
        var counter = 0;

        // get the session varible if it exists    
        if (Session["counter"] != null)
        {
            counter = (int) Session["counter"];
        }

        // increment it
        counter++;

        // save it
        Session["counter"] = counter;

        // make an associative array of senders we know, indexed by phone number
        var people = new Dictionary<string, string>()
        {
            {"+14158675309", "Rey"},
            {"+14158675310", "Finn"},
            {"+14158675311", "Chewy"}
        };

        // if the sender is known, then greet them by name
        var name = "Friend";
        if (people.ContainsKey(request.From))
        {
            name = people[request.From];
        }

        var response = new TwilioResponse();
        response.Message($"{name} has messaged {request.To} {counter} times");
        return TwiML(response);
    }
}
// In Package Manager, run:
// Install-Package Twilio.AspNet.Mvc -DependencyVersion HighestMinor

using System.Collections.Generic;
using System.Web.Mvc;
using Twilio.AspNet.Mvc;
using Twilio.TwiML;

public class SmsController : TwilioController
{
    [HttpPost]
    public ActionResult Index()
    {
        var counter = 0;

        // get the session varible if it exists
        if (Session["counter"] != null)
        {
            counter = (int) Session["counter"];
        }

        // increment it
        counter++;

        // save it
        Session["counter"] = counter;

        // make an associative array of senders we know, indexed by phone number
        var people = new Dictionary<string, string>()
        {
            {"+14158675309", "Rey"},
            {"+14158675310", "Finn"},
            {"+14158675311", "Chewy"}
        };

        // if the sender is known, then greet them by name
        var name = "Friend";
        var from = Request.Form["From"];
        var to = Request.Form["To"];
        if (people.ContainsKey(from))
        {
            name = people[from];
        }

        var response = new MessagingResponse();
        response.Message($"{name} has messaged {to} {counter} times");

        return TwiML(response);
    }
}
Tracking SMS Conversations using Cookies

It's almost too easy, isn't it? If you're looking for a more complex example of using cookies to track a conversation, take a look at our Employee Directory tutorial.

David Prothero
Jarod Reyes

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
SDK Version:
  • 4.x
  • 5.x
// In Package Manager, run:
// Install-Package Twilio.Mvc -DependencyVersion HighestMinor

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

public class SmsController : TwilioController
{
    [HttpPost]
    public ActionResult Index(SmsRequest request)
    {
        var counter = 0;

        // get the session varible if it exists    
        if (Session["counter"] != null)
        {
            counter = (int) Session["counter"];
        }

        // increment it
        counter++;

        // save it
        Session["counter"] = counter;

        // make an associative array of senders we know, indexed by phone number
        var people = new Dictionary<string, string>()
        {
            {"+14158675309", "Rey"},
            {"+14158675310", "Finn"},
            {"+14158675311", "Chewy"}
        };

        // if the sender is known, then greet them by name
        var name = "Friend";
        if (people.ContainsKey(request.From))
        {
            name = people[request.From];
        }

        var response = new TwilioResponse();
        response.Message($"{name} has messaged {request.To} {counter} times");
        return TwiML(response);
    }
}
// In Package Manager, run:
// Install-Package Twilio.AspNet.Mvc -DependencyVersion HighestMinor

using System.Collections.Generic;
using System.Web.Mvc;
using Twilio.AspNet.Mvc;
using Twilio.TwiML;

public class SmsController : TwilioController
{
    [HttpPost]
    public ActionResult Index()
    {
        var counter = 0;

        // get the session varible if it exists
        if (Session["counter"] != null)
        {
            counter = (int) Session["counter"];
        }

        // increment it
        counter++;

        // save it
        Session["counter"] = counter;

        // make an associative array of senders we know, indexed by phone number
        var people = new Dictionary<string, string>()
        {
            {"+14158675309", "Rey"},
            {"+14158675310", "Finn"},
            {"+14158675311", "Chewy"}
        };

        // if the sender is known, then greet them by name
        var name = "Friend";
        var from = Request.Form["From"];
        var to = Request.Form["To"];
        if (people.ContainsKey(from))
        {
            name = people[from];
        }

        var response = new MessagingResponse();
        response.Message($"{name} has messaged {to} {counter} times");

        return TwiML(response);
    }
}