Receive an incoming SMS Message

Note:

Before you can get started, you need the following already set up:

Learn how to handle incoming SMS messages in a .Net Core MVC application with the Sinch SMS API.

Steps:
  1. Set up your .NET Core application
  2. Configure your Callback URL
  3. Test the application

Set up your .Net Core application

  1. Create a new folder where you want your app project. Then, open a terminal or command prompt to that location.
  2. Create a new .Net Core MVC app with the following command:
    Copy
    Copied
    dotnet new mvc
  3. Add the Newtonsoft.Json nuget package:
    Copy
    Copied
    dotnet add package Newtonsoft.Json

Modify your application

  1. In the Controllers folder of your project, create a new file named InboundController.cs.
  2. Populate that file with the "Handle receiving an SMS message" code found on this page.

    Handle receiving an SMS message

    // Find your Service Plan ID and API Token at dashboard.sinch.com/sms/api/rest
    using System;
    using System.Net.Http;
    using System.Net;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Newtonsoft.Json;
    
    public class InboundSMS
    {
        public string body { get; set; }
        public string from { get; set; }
        string id { get; set; }
        string operator_id { get; set; }
        string received_at { get; set; }
        public string to { get; set; }
        string type { get; set; }
    }
    public class InboundController : Controller
    {
        public string servicePlanId = "YOUR_servicePlanId";
        public string apiToken = "YOUR_API_Token";
        
        [HttpPost]
        public async Task<HttpResponseMessage> ReceiveMessage([FromBody]InboundSMS inboundSms)
        {
            HttpResponseMessage res = new HttpResponseMessage();
            try 
            {
                Console.WriteLine(inboundSms.body);
                SMS sms = new SMS(inboundSms.to, new string[] { inboundSms.from }, inboundSms.body);
                var response = await sms.sendSMS(sms, servicePlanId, apiToken);
                Console.WriteLine(sms.body);
                res.StatusCode = HttpStatusCode.OK;
    
                return res;
            }
            catch
            {
                res.StatusCode = HttpStatusCode.BadRequest;
                return res;
            }
        }
    }
    public class SMS
    {
        public string from { get; set; }
        public string[] to { get; set; } 
        public string body { get; set; }
        
        public SMS(string fromVar, string[] toVar, string bodyVar)
        {
            from = fromVar;
            to = toVar;
            body = "Your message was: " + bodyVar;
        }
    
        public async Task<string> sendSMS(SMS sms, string servicePlanId, string apiToken)
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + apiToken);
                string json = JsonConvert.SerializeObject(sms);
                var postData = new StringContent(json, Encoding.UTF8, "application/json");
                var request = await client.PostAsync("https://us.sms.api.sinch.com/xms/v1/" + servicePlanId + "/batches", postData);
                var response = await request.Content.ReadAsStringAsync();
                
                return response;
            }
        }
    }
  3. Save the file.

Fill in your parameters

  1. Back in the Program.cs file, replace the following values for these parameters with your values:
ParameterYour value
YOUR_Sinch_virtual_numberAny number you've assigned to your Sinch account. Find the number on your Sinch dashboard by clicking the service plan ID link and scrolling to the bottom of the page.
recipient_numberThe phone number to which you want to send the test SMS message.
YOUR_servicePlanIdThe API token found on your Sinch dashboard. Click Show to reveal your API token.
YOUR_API_tokenThe service plan ID found on your Sinch dashboard.
  1. Save the file.

Build your project

Before executing your code, you must first compile your application. Execute the following command:

Copy
Copied
dotnet build

Start your web server and set up a tunnel

  1. Start the server by executing the following command:
    Copy
    Copied
    dotnet run

    By default, your web server is started on port 5001.

  2. Open a tunnel to the server you just set up. We are using ngrok for this. If you don't have ngrok installed already, install it with the following command:
    Copy
    Copied
    npm install ngrok -g
  3. Open a terminal or command prompt and enter:
    Copy
    Copied
    ngrok http https://localhost:5001
  4. Copy the HTTPS address that ends with .ngrok.io and add /Inbound/ReceiveMessage to the end of it.

Configure your Callback URL

  1. To configure a callback URL for your Sinch account, login to your dashboard.
  2. Click on the service plan ID link and edit the Callback URL field with the ngrok.io domain URL from the previous step.

Send your SMS message

Now send an SMS message to your Sinch number from your mobile phone and you will get an automatic reply.

Next steps

The code you used in the Inbound.cs file sends a POST request to the Sinch API /batches endpoint to send the SMS message.

Additional resources

  • Click here to read more about the batches endpoint.
Was this page helpful?

Handle receiving an SMS message

// Find your Service Plan ID and API Token at dashboard.sinch.com/sms/api/rest
using System;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

public class InboundSMS
{
    public string body { get; set; }
    public string from { get; set; }
    string id { get; set; }
    string operator_id { get; set; }
    string received_at { get; set; }
    public string to { get; set; }
    string type { get; set; }
}
public class InboundController : Controller
{
    public string servicePlanId = "YOUR_servicePlanId";
    public string apiToken = "YOUR_API_Token";
    
    [HttpPost]
    public async Task<HttpResponseMessage> ReceiveMessage([FromBody]InboundSMS inboundSms)
    {
        HttpResponseMessage res = new HttpResponseMessage();
        try 
        {
            Console.WriteLine(inboundSms.body);
            SMS sms = new SMS(inboundSms.to, new string[] { inboundSms.from }, inboundSms.body);
            var response = await sms.sendSMS(sms, servicePlanId, apiToken);
            Console.WriteLine(sms.body);
            res.StatusCode = HttpStatusCode.OK;

            return res;
        }
        catch
        {
            res.StatusCode = HttpStatusCode.BadRequest;
            return res;
        }
    }
}
public class SMS
{
    public string from { get; set; }
    public string[] to { get; set; } 
    public string body { get; set; }
    
    public SMS(string fromVar, string[] toVar, string bodyVar)
    {
        from = fromVar;
        to = toVar;
        body = "Your message was: " + bodyVar;
    }

    public async Task<string> sendSMS(SMS sms, string servicePlanId, string apiToken)
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + apiToken);
            string json = JsonConvert.SerializeObject(sms);
            var postData = new StringContent(json, Encoding.UTF8, "application/json");
            var request = await client.PostAsync("https://us.sms.api.sinch.com/xms/v1/" + servicePlanId + "/batches", postData);
            var response = await request.Content.ReadAsStringAsync();
            
            return response;
        }
    }
}