Twilio with .NET Core
Twilio with .NET Core
Categories:
2 minute read
Last night after reading this tweet, I decided to try out Twilio with .NET Core
Your feedback led to the newly redesigned C# helper library.
See what's new and take it for a spin here: https://t.co/IuD4NZLBH9 pic.twitter.com/SzLB7udU1h— twilio (@twilio) February 28, 2017
Let’s create the sample console app:
Create the application
Open a command prompt and run
md twilio.console
cd twilio.console
dotnet new
dotnet restore
code .
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"
}
}
}
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;
}
}
}
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/main/twilio.console
Hope it helps!