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

1    md twilio.console
2    cd twilio.console
3    dotnet new
4    dotnet restore
5    code .

2. Replace the contents of project.json#


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

 1{
 2  "version": "1.0.0-*",
 3  "buildOptions": {
 4    "debugType": "portable",
 5    "emitEntryPoint": true
 6  },
 7  "dependencies": {
 8    "Twilio": "5.0.2"
 9  },
10  "frameworks": {
11    "netcoreapp1.1": {
12      "dependencies": {
13        "Microsoft.NETCore.App": {
14          "type": "platform",
15          "version": "1.1.0"
16        }
17      },
18      "imports": "dnxcore50"
19    }
20  }
21}

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.

 1using System;
 2using System.Threading.Tasks;
 3using Twilio;
 4using Twilio.Rest.Api.V2010.Account;
 5using Twilio.Types;
 6
 7namespace ConsoleApplication
 8{
 9    public class Program
10    {
11        public static void Main(string[] args)
12        {
13            // Send the SMS
14            var messageSid = Task.Run(() => 
15            { 
16                return SendSms(); 
17            })
18            .GetAwaiter()
19            .GetResult();
20
21            // Write the message Id to the console.
22            Console.WriteLine(messageSid);
23            Console.Read();
24        }
25
26        // Send SMS with async feature!
27        public static async Task<string> SendSms()
28        {
29            // Your Account SID from twilio.com/console
30            var accountSid = "[Account SID]";
31
32            // Your Auth Token from twilio.com/console
33            var authToken = "[Auth Token]";
34
35            // Initialize Twilio Client
36            TwilioClient.Init(accountSid, authToken);
37
38            // Create & Send Message (New lib supports async await)
39            var message = await MessageResource.CreateAsync(
40                to: new PhoneNumber("[Target Phone Number]"),
41                from: new PhoneNumber("[Your Twilio Phone Number]"),
42                body: "Hello from dotnetcore");
43
44            return message.Sid;
45        }
46    }
47}

4. Run the application#


Open a command prompt and run

1    dotnet restore
2    dotnet run

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

Hope it helps!