Add Programmable SMS to Your .NET Apps

The Nexmo SMS API lets you send and receive text messages around the world without having to worry about which carriers the recipients are subscribed to. This tutorial shows you how to use the Nexmo C# Client Library to send and receive SMS messages from your ASP.NET MVC web app.

GitHub icon View the source code on GitHub

Prerequisites

To get started with the Nexmo Client Library for .NET, you will need:

  • Visual Studio 2017
  • A Windows machine

Getting Started

Sign up for a Nexmo account and get your API credentials from the Getting Started page of the dashboard. The credentials to look for include the Nexmo API Key, the Nexmo API Secret, the Nexmo Virtual Number. You will be adding these credentials to your project in order to communicate with the Nexmo API. Navigate to the Numbers section of the dashboard to buy a phone number.

ASP.NET Project Setup

First, open up Visual Studio and create a new ASP.NET Web Application (.NET Framework) project.

Open up Visual Studio and create a new ASP.NET Web Application (.NET Framework) project

Select the MVC Template and ensure the Authentication type is set to No Authentication. Click OK to create the project.

Select the MVC Template and ensure the Authentication type is set to No Authentication. Click OK to create the project

Next, install the Nexmo C# Client Library via the NuGet Package Manager Console.

Install-Package Nexmo.Csharp.Client -Version 2.2.2'
Install the Nexmo C# Client Library via the NuGet Package Manager Console

Also, add the following package to enable debug logging in the output window via the Package Manager Console:

Install-Package Microsoft.Extensions.Logging -Version 1.0.1

Next, under the Tools dropdown menu, locate NuGet Package Manager and click Manage NuGet Packages for Solution. Under the Updates tab, select the Update All Packages box and click the Update button.

Manage NuGet Packages for Solution

Diving Into the ASP.NET Project Code

Add a JSON file (appsettings.json) to your project. Inside this file, add your Nexmo credentials.

{
    "appSettings": {    
        "Nexmo.UserAgent": "NEXMOQUICKSTART/1.0",
        "Nexmo.Url.Rest": "https://rest.nexmo.com",
        "Nexmo.Url.Api": "https://api.nexmo.com",
        "Nexmo.api_key": "NEXMO-API-KEY",
        "Nexmo.api_secret": "NEXMO-API-SECRET",
        "NEXMO_FROM_NUMBER": "NEXMO-VIRTUAL-NUMBER"
    }
}

Create a new controller (SMSController.cs). In this controller, create an action method called Send. Above the method, add a HttpGetAttribute to allow the user to navigate to the corresponding view.

[System.Web.Mvc.HttpGet]
public ActionResult Send()
{
    return View();
}

Afterwards, click on the Views folder and add a new folder called SMS. Within this folder, create a new view (`Send.cshtml'). Then, add a form to the view with two input tags (type = "text") for the destination number and the message to be sent. Lastly, add an input tag (type = "submit") to submit the form.


@using (Html.BeginForm("Send", "Home", FormMethod.Post))
{
 
    <input id="to" name="to" type="text" placeholder="To" />
    <input id="text" name="text" type="text" placeholder="Text" />
    <input type="submit" value="Send" />
}

Back in the SMSController, add the following using statement to the top of the file.

using Nexmo.Api;

Add another action method named Send with two string parameters: to and text. Within this method, add the code below to send the text using the parameters as the to and text values. The from number is your Nexmo virtual number (retrieved from the appsettings.json).

[System.Web.Mvc.HttpPost]
public ActionResult Send(string to, string text)
{
    var results = SMS.Send(new SMS.SMSRequest
    {
        from = Configuration.Instance.Settings["appsettings:NEXMO_FROM_NUMBER"],
        to = to,
        text = text
    });
    return View();
}

Run the app and navigate to the correct route localhost:PORT/SMS/Send. Enter the message you wish to send and the destination number and click Send.

Enter the message you wish to send and the destination number

Received message

There you have it! Sending an SMS in .NET using the Nexmo C# Client Library is that simple! Next, we'll move on to receiving an SMS in .NET Standard!

Receiving Webhooks on Your Localhost with Ngrok

The Nexmo SMS API uses webhooks to inform your ASP.NET web application that an incoming text message has been sent to one of your Nexmo phone numbers. In order to do this, Nexmo needs to be able to make an HTTP request to a public URL. Since we're developing our app on a local machine, we need to create a local tunnel that gives our machine a public URL.

We will be using ngrok to expose the port over the internet to easily communicate with the Nexmo platform during this testing phase. This approach saves you from having to deploy your application.

Download ngrok and run the following command in Command Prompt (replace the port number with the number of the port you wish to run the app on).

ngrok http 8080 -host-header="localhost:8080"
ngrok Command Prompt. Replace the port number with the number of the port you wish to run the app on

The command above allows your local server (running on the port above) to have a public URL that will be used to forward the incoming texts (HTTP requests) back to your local server. The host header needs to be specified to make sure the host header of the application and ngrok match and to ensure the requests will not be rejected.

Diving Into Code

Continuing the project from the previous section, let's create an action method called 'Receive' in SMSController.cs. This path will be receiving the inbound SMS data as we will be setting the Nexmo webhook (later in this tutorial) to our ngrok URL with the route of 'SMS/Receive'.

Add [FromUri] in the parameter to read the incoming SMS. Above this method, add an HTTPGetAttribute to restrict the method to accepting only GET requests. If the value for response.to (the Nexmo phone number) and msidsn (the sender) are not null, print out the message to the output window using Debug.WriteLine. Otherwise, the endpoint was hit as a result of something other than an incoming SMS. (This can happen when you first set up your webhook. You'll see this shortly.)

[System.Web.Mvc.HttpGet]
public ActionResult Receive([FromUri]SMS.SMSInbound response)
{
    if (null != response.to && null != response.msisdn)
    {
        Debug.WriteLine("-------------------------------------------------------------------------");
        Debug.WriteLine("INCOMING TEXT");
        Debug.WriteLine("From: " + response.msisdn);
        Debug.WriteLine(" Message: " + response.text);
        Debug.WriteLine("-------------------------------------------------------------------------");
        return new HttpStatusCodeResult(200);
    }
    else {
        Debug.WriteLine("-------------------------------------------------------------------------");
        Debug.WriteLine("Endpoint was hit.");
        Debug.WriteLine("-------------------------------------------------------------------------");
        return new HttpStatusCodeResult(200);
    }
}

Run the ASP.NET Web App

In the Solution Explorer, expand the project and click Properties. Click the Web tab and change the Project URL to the same port you are exposing via ngrok. Finally, run the project.

In the ASP.NET Web App Solution Explorer, expand the project and click Properties. Click the Web tab and change the Project URL to the same port you are exposing via ngrok; run the project

 

Set the SMS Callback Webhook URL for Your Nexmo Number

Next, head over to the Nexmo Dashboard and navigate to the Settings page. Towards the bottom, you will see Callback for Inbound SMS under the API Settings. Paste the ngrok URL inside the textbox and add /SMS/Receive to the end of it. This will route the message to Receive action in the SMS controller.

Nexmo Dashboard Settings page

If you prefer to use a command line interface, you can also achieve this using the Nexmo CLI. Open up Terminal and install the Nexmo CLI via npm. Next, set up the CLI with your api_key and api_secret to link your Nexmo account. Lastly, update the callback URL for the Nexmo number you chose to receive the SMS messages on.

npm install nexmo-cli -g
nexmo setup api_key api_secret
nexmo link:sms 1231231234 https://www.example.ngrok.io/SMS/Receive

Receive an SMS with ASP.NET

You are ready to go! With your ASP.NET web app running, open up the output window in Visual Studio. Send an SMS to your Nexmo phone number and you will see the incoming texts coming through! Your ASP.NET web app is able to receive SMS messages that are sent to your Nexmo phone number via an inbound webhook!

Rabeb Othmani Rabeb is a developer advocate at Nexmo focusing on cloud communication APIs and helping developers getting the best experience possible when building their apps. All of this while consuming good quality coffee, obviously! Other than writing code for a living, Rabeb advocates to bring more women and minorities into tech, thus her involvement with Women Who Code and different tech communities. She is leading the Women Who Code Network in Bristol.
 

Comments