Register by 10/16 for $250 off the on-site price.

Programmable SMS Quickstart for C# with .NET Core

Looking for .NET Framework? We have a quickstart for that too!

With just a few lines of code, your .NET Core application can send and receive text messages with Twilio Programmable SMS.

This C# SMS Quickstart will teach you how to do this using our Communications REST API and the Twilio helper library for .NET Core.

In this Quickstart, you will learn how to:

  1. Sign up for Twilio and get your first SMS-enabled Twilio phone number
  2. Set up your development environment to send and receive messages
  3. Send your first SMS
  4. Receive inbound text messages
  5. Reply to incoming messages with an SMS

Prefer to get started by watching a video? Check out our C# SMS Quickstart video on Youtube.

If you already have a Twilio account and an SMS-enabled Twilio phone number, you’re all set here! Feel free to jump to the next step.

Before you can send an SMS from C#, you'll need to sign up for a Twilio account or sign into your existing account and purchase an SMS-capable phone number.

You can sign up for a free Twilio trial account here.

  • When you sign up, you'll be asked to verify your personal phone number. This helps Twilio verify your identity and also allows you to send test messages to your phone from your Twilio account while in trial mode.
  • Once you verify your number, you'll be asked to create a project. For the sake of this tutorial, you can click on the "Learn and Explore" template. Give your project a name, or just click "skip remaining steps" to continue with the default.
  • Once you get through the project creation flow, you'll arrive at your project dashboard in the Twilio Console. This is where you'll be able to access your Account SID, authentication token, find a Twilio phone number, and more.

If you don't currently own a Twilio phone number with SMS functionality, you'll need to purchase one.  After navigating to the Buy a Number page, check the "SMS" box and click "Search."

Buy a SMS-Capable Twilio Phone Number

You’ll then see a list of available phone numbers and their capabilities. Find a number that suits your fancy and click "Buy" to add it to your account.

Select an SMS-enabled phone number

Now that you have a Twilio account and a programmable phone number, you can start writing some code! To make things even easier, we'll install Twilio's official helper for .NET Core applications.

Install .NET Core

You can check if you already have .NET Core installed on your machine by opening up a command prompt or terminal and running the following command:

dotnet --version

You should see something like 2.1.3. If you receive an error message, you can download .NET Core from Microsoft and install it.

Create a new project and add the Twilio NuGet package

Run these commands to create a new .NET project and install the Twilio NuGet package:

mkdir TwilioSend
cd TwilioSend
dotnet new console
dotnet add package Twilio

Send an outbound SMS message with C#

Now that we have .NET Core and the Twilio .NET NuGet package installed, we can send an outbound text message from the Twilio phone number we just purchased with a single API request. Open the file in your new project called Program.cs and type or paste in this code sample, replacing the template code that's already there.

Loading Code Samples...
Language
SDK Version:
  • 5.x
Format:
  • JSON
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;


class Program 
{
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var message = MessageResource.Create(
            body: "Join Earth's mightiest heroes. Like Kevin Bacon.",
            from: new PhoneNumber("+15017122661"),
            to: new PhoneNumber("+15558675310")
        );

        Console.WriteLine(message.Sid);
    }
}
{
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "api_version": "2010-04-01",
  "body": "Join Earth's mightiest heroes. Like Kevin Bacon.",
  "date_created": "Thu, 30 Jul 2015 20:12:31 +0000",
  "date_sent": "Thu, 30 Jul 2015 20:12:33 +0000",
  "date_updated": "Thu, 30 Jul 2015 20:12:33 +0000",
  "direction": "outbound-api",
  "error_code": null,
  "error_message": null,
  "from": "+15017122661",
  "messaging_service_sid": "MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "num_media": "0",
  "num_segments": "1",
  "price": -0.00750,
  "price_unit": "USD",
  "sid": "MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "status": "sent",
  "subresource_uris": {
    "media": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Media.json"
  },
  "to": "+15558675310",
  "uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json"
}
This code creates a new instance of the Message resource.
Send an SMS Using Twilio with C#

This code creates a new instance of the Message resource.

You’ll need to edit this file a little more before your message will send:

Replace the placeholder credential values

Swap the placeholder values for accountSid and authToken with your personal Twilio credentials. Go to https://www.twilio.com/console and log in. On this page, you’ll find your unique Account SID and Auth Token, which you’ll need any time you send messages through the Twilio Client like this. You can reveal your auth token by clicking on the 'view' link:

Reveal your Auth Token in the Twilio Console

Edit Program.cs and replace the values for accountSid and authToken with your unique values.

Please note: it's okay to hardcode your credentials when getting started, but you should use configuration to keep them secret before deploying to production. We've written blog posts on how to secure user secrets in a .NET Core Web App and a .NET Core Console App that should provide you with some good guidance.

Replace the "from" phone number

Remember that SMS-enabled phone number you bought just a few minutes ago? Go ahead and replace the existing from number with that one, making sure to use E.164 formatting:

[+][country code][phone number including area code]

Replace the "to" phone number

Replace the to phone number with your mobile phone number. This can be any phone number that can receive text messages, but it’s a good idea to test with your own phone, so you can see the magic happen! As above, you should use E.164 formatting for this value.

If you are on a Twilio Trial account, your outgoing SMS messages are limited to phone numbers that you have verified with Twilio. Phone numbers can be verified via your Twilio Console's Verified Caller IDs.

Save your changes and run this code:

dotnet run

That's it! In a few moments, you should receive an SMS from your Twilio number on your phone.

Are your customers in the U.S. or Canada? You can also send them MMS messages by adding just one line of code. Check out this sending MMS tutorial to see how it's done.

Receive and reply to inbound SMS messages with ASP.NET Core

When your Twilio number receives an incoming message, Twilio will send an HTTP request to a server you control. This callback mechanism is known as a webhook.  When Twilio sends your application a request, it expects a response in the TwiML XML format telling it how to respond to the message. Let's see how we would build this in C# using ASP.NET Core.

Create a new ASP.NET Core project

Run these commands to create a new ASP.NET Core project and install the Twilio NuGet package:

mkdir TwilioReceive
cd TwilioReceive
dotnet new mvc
dotnet add package Twilio.AspNet.Core

Create a new controller

In the directory named Controllers, create a new Controller called SmsController.cs and use the following code to create a server that can handle incoming messages.

Loading Code Samples...
Language
// Code sample for ASP.NET Core on .NET Core
// From command prompt, run:
// dotnet add package Twilio.AspNet.Core

using Twilio.AspNet.Common;
using Twilio.AspNet.Core;
using Twilio.TwiML;

namespace TwilioReceive.Controllers
{
    public class SmsController : TwilioController
    {
        public TwiMLResult Index(SmsRequest incomingMessage)
        {
            var messagingResponse = new MessagingResponse();
            messagingResponse.Message("The copy cat says: " +
                                      incomingMessage.Body);

            return TwiML(messagingResponse);
        }
    }
}
When your phone number receives an incoming message, Twilio will send an HTTP request to your server. This code shows how your server should respond to reply with a text message (using TwiML).
Respond to an incoming text message

When your phone number receives an incoming message, Twilio will send an HTTP request to your server. This code shows how your server should respond to reply with a text message (using TwiML).

You now need to make your application accessible over the internet. While you can do that in any number of ways, we recommend a tool that provides an externally accessible URL called ngrok. We'll show you how to set that up next so your app can receive messages.

Allow Twilio to talk to your ASP.NET Core application with ngrok

We’ve just built a small ASP.NET Core application to receive incoming messages. Before it will work, we need to make sure that Twilio can reach your application.

Most Twilio services use webhooks to communicate with your application. When Twilio receives an SMS, for example, it reaches out to a URL in your application for instructions on how to handle the message.

When you’re working on your ASP.NET Core application in your development environment, your app is only reachable by other programs on your computer, so Twilio won’t be able to talk to it. We need to solve this problem by making your application accessible over the internet.

While there are a lot of ways to do this, like deploying your application to Azure or AWS, you'll probably want a less laborious way to test your Twilio application. For a lightweight way to make your app available on the internet, we recommend a tool called ngrokNgrok listens on the same port that your local web server is running on and provides a unique URL on the ngrok.io domain, forwarding incoming requests to your local development environment. It works something like this:

How ngrok helps Twilio reach your local server

If you haven't done so already, download and install ngrok. For more info on ngrok, including some great tips and tricks, check out this in-depth blog post.

Change your application's launch settings

Once you have ngrok downloaded, you need to make one small change to the Properties/launchSettings.json file. Find the line that has:

"applicationUrl": "https://localhost:5001;http://localhost:5000",

And change it to:

"applicationUrl": "http://localhost:5000",

This change is needed because ngrok will create a secure tunnel for you but will not work with the self-signed certificate that ASP.NET Core provides.

Start your ASP.NET Core application

Start your application by running:

dotnet run

You should see Now listening on: http://localhost:5000. You can try opening http://localhost:5000/sms in the browser and see the TwiML response we will be sending to Twilio. As we discussed, however, Twilio can't find your localhost, so we need one more step.

Start the ngrok tunnel

Now, start up ngrok on port 5000:

ngrok http 5000

You should see something like the following:

Ngrok Extensions for Visual Studio - running

Now we have a new external URL.

Configure your webhook URL

For Twilio to know where to look, you need to configure your Twilio phone number to call your webhook URL whenever a new message comes in.

  1. Log into Twilio.com and go to the Console's Numbers page.
  2. Click on your SMS-enabled phone number.
  3. Find the Messaging section. The default “CONFIGURE WITH” is what you’ll need: "Webhooks, TwiML, [etc.]".
  4. In the “A MESSAGE COMES IN” section, select "Webhook" and paste in your URL: in this quickstart step above, it would be: https://354f5b25.ngrok.io/sms - be sure to add /sms at the end, as this is the route to your SmsController class.

configure-phone-number

 Save your changes - you’re ready!

Test your application

Make sure your project is running and your ngrok tunnel is running. If you restarted ngrok, you will have to update your webhook in the console to use the right URL.

With both of those servers running, we’re ready for the fun part - testing our new ASP.NET Core SMS application! 

Send an SMS from your mobile phone to your Twilio phone number that's configured with this webhook. You should see an HTTP request in your ngrok console. Your ASP.NET Core app will process the text message, and you’ll get your response back as an SMS.

Where to next?

Now that you know the basics of sending and receiving SMS and MMS text messages with C# and .NET, you might want to check out these resources.

Happy hacking!

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.

Loading Code Samples...
SDK Version:
  • 5.x
Format:
  • JSON
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;


class Program 
{
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var message = MessageResource.Create(
            body: "Join Earth's mightiest heroes. Like Kevin Bacon.",
            from: new PhoneNumber("+15017122661"),
            to: new PhoneNumber("+15558675310")
        );

        Console.WriteLine(message.Sid);
    }
}
{
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "api_version": "2010-04-01",
  "body": "Join Earth's mightiest heroes. Like Kevin Bacon.",
  "date_created": "Thu, 30 Jul 2015 20:12:31 +0000",
  "date_sent": "Thu, 30 Jul 2015 20:12:33 +0000",
  "date_updated": "Thu, 30 Jul 2015 20:12:33 +0000",
  "direction": "outbound-api",
  "error_code": null,
  "error_message": null,
  "from": "+15017122661",
  "messaging_service_sid": "MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "num_media": "0",
  "num_segments": "1",
  "price": -0.00750,
  "price_unit": "USD",
  "sid": "MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "status": "sent",
  "subresource_uris": {
    "media": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Media.json"
  },
  "to": "+15558675310",
  "uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json"
}
// Code sample for ASP.NET Core on .NET Core
// From command prompt, run:
// dotnet add package Twilio.AspNet.Core

using Twilio.AspNet.Common;
using Twilio.AspNet.Core;
using Twilio.TwiML;

namespace TwilioReceive.Controllers
{
    public class SmsController : TwilioController
    {
        public TwiMLResult Index(SmsRequest incomingMessage)
        {
            var messagingResponse = new MessagingResponse();
            messagingResponse.Message("The copy cat says: " +
                                      incomingMessage.Body);

            return TwiML(messagingResponse);
        }
    }
}