Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Hosted-services / Azure

Receive and Reply to a Twilio SMS in Azure C#

2.00/5 (2 votes)
15 Dec 2020CPOL 4.6K  
How to receive and reply to a Twilio SMS in Azure C#
In this tip, you will see how I use HttpUtility because both methods provided by Microsoft to access POST parameters were not working.

Introduction

Neither Twilio nor Microsoft provide code samples to bind incoming SMS from Twilio to Azure function.

This tip is the equivalent of this post from Twilio, but related to Azure, not PHP.

The solution is as given below.

Background

  • Having an Azure account and knowing how to implement an Azure function HTTP Trigger with C#
  • Having a Twilio account with valid phone number and knowing how to hookup incoming SMS to an URL

Using the Code

  • In Microsoft Azure, Copy/Paste function code in your project.
  • In Microsoft Azure, copy function URL.
  • In Twilio, paste URL into the Messaging Webhook section (keep all parameters with default value).
  • Test: Send an SMS, you get it into variables From, To, and Body.
C++
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace TwilioToAzure
{
    class TwilioAzure
    {
        [FunctionName("Twilio")]
        public static async Task<IActionResult> Run(
           [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] 
            HttpRequest req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request. ");

            var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var queryParams = HttpUtility.ParseQueryString(requestBody);
                               
            var To = queryParams["To"];
            var From = queryParams["From"];
            var Body = queryParams["Body"];
                               
            //return new OkObjectResult("OK"); <-Extra tip: Twilio will reply "OK" SMS 
            return new OkObjectResult(""); //Twilio will not reply
        }
    }
}

Points of Interest

I wrote this tip because both methods provided by Microsoft to access POST parameters were not working. So I had to use HttpUtility instead.

History

  • 15th December, 2020: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)