Twilio with .NET Core

by Carlos Mendible on 02 Mar 2017 » dotNetCore

Last night after reading this tweet, I decided to try out Twilio with .NET Core

Let’s create the sample console app:

1. Create the application


Open a command prompt and run

    md twilio.console
    cd twilio.console
    dotnet new
    dotnet restore
    code .

2. Replace the contents of project.json


Replace the contents on project.json file in order to include the references to: Twilio

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {
    "Twilio": "5.0.2"
  },
  "frameworks": {
    "netcoreapp1.1": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.1.0"
        }
      },
      "imports": "dnxcore50"
    }
  }
}

3. Replace the contents of Program.cs


The CreateClass method is where the magic occurs. Each relevant line is explained to help you understand each step.

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

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // Send the SMS
            var messageSid = Task.Run(() => 
            { 
                return SendSms(); 
            })
            .GetAwaiter()
            .GetResult();

            // Write the message Id to the console.
            Console.WriteLine(messageSid);
            Console.Read();
        }

        // Send SMS with async feature!
        public static async Task<string> SendSms()
        {
            // Your Account SID from twilio.com/console
            var accountSid = "[Account SID]";

            // Your Auth Token from twilio.com/console
            var authToken = "[Auth Token]";

            // Initialize Twilio Client
            TwilioClient.Init(accountSid, authToken);

            // Create & Send Message (New lib supports async await)
            var message = await MessageResource.CreateAsync(
                to: new PhoneNumber("[Target Phone Number]"),
                from: new PhoneNumber("[Your Twilio Phone Number]"),
                body: "Hello from dotnetcore");

            return message.Sid;
        }
    }
}

4. Run the application


Open a command prompt and run

    dotnet restore
    dotnet run

Get a copy of the code here: https://github.com/cmendible/dotnetcore.samples/tree/master/twilio.console

Hope it helps!