DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core
  • Revolutionizing Content Management
  • Revolutionizing API Development: A Journey Through Clean Architecture With Adapter Pattern in ASP.NET Core

Trending

  • MySQL to PostgreSQL Database Migration: A Practical Case Study
  • AWS to Azure Migration: A Cloudy Journey of Challenges and Triumphs
  • How to Perform Custom Error Handling With ANTLR
  • Data Quality: A Novel Perspective for 2025
  1. DZone
  2. Data Engineering
  3. Databases
  4. Sending SMS Using ASP.NET Core With the Twilio SMS API

Sending SMS Using ASP.NET Core With the Twilio SMS API

In this tutorial, you'll learn how to install and configure the Twilio SMS API package to send SMS messages with ASP.NET Core.

By 
Rajeesh Menoth user avatar
Rajeesh Menoth
·
Dec. 14, 17 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
15.5K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we will explain how to send SMS using ASP.NET Core with the Twilio SMS API. Twilio provides a third-party SMS API for sending SMS over the global network.

Before reading this article, read the articles given below for ASP.NET Core knowledge.

  • Getting started with ASP.NET Core 1.0

  • Project Layout In Asp.Net Core 1.0

  • Middleware And Staticfiles in Asp.Net Core 1.0 – Part 1

  • Middleware And Staticfiles in Asp.Net Core 1.0 – Part 2

Package Installation

  1. Install-Package Twilio -Version 5.9.1. This package will install all the SMS, video, and related classes, methods, and APIs for Twilio.

  2. Install-Package jQuery.Validation.Unobtrusive -Version 2.0.20710. This package will install all the bootstrap and validation related Jquery libraries in our project.

Important Notes:

  1. If you don’t have a Twilio account, then you should register a free account here and choose the language C#.

  2. Once registration is completed, then we can access the Dashboard and Console of our Twilio account. We will get the Account SID & Auth Token ID from the Dashboard for sending SMS.

  3. Image title

  4. We need a Twilio From number because that number has sent SMS to the global network, so we need to enable Twilio SMS number (this will send SMS from your "To" numbers). Go to this link here and click on the "Get a number" button in the "Programmble SMS Menu" in the following screenshot.

  5. Image title

  6. You have to get $15 for sending SMS in a Twilio trial account. I can see in my account they are charging $1 + for each SMS, and after that, you need to buy a paid plan.

Name Spaces

The following namespaces provide ASP.Net Core MVC & Twilio SMS API classes and methods.

using System;
using Microsoft.AspNetCore.Mvc;
using RegistrationForm.ViewModels;
using Twilio;
using Twilio.Types;
using Twilio.Rest.Api.V2010.Account;

Configuring ASP.NET MVC in ASP.NET Core

We are going to add "UseMvc" middleware and "AddMvc()" configure services in the Startup.cs class. The code given below clearly mentions that we need to manually add our controller name and an action name in "MapRoute." We can change this controller name and action name, which are based on our requirement in the application.

app.UseMvc(routes =>
           {
               routes.MapRoute(
                   name: "default",
                   template: "{controller=Home}/{action=Index}/{id?}");
           });

Startup.cs

The class given below contains the complete middleware details for our application. I choose a default project in Visual Studio 2015. Automatically, it will generate the following classes and methods.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace SMSApp
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

            if (env.IsDevelopment())
            {
                // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
                builder.AddApplicationInsightsSettings(developerMode: true);
            }
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseApplicationInsightsRequestTelemetry();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseApplicationInsightsExceptionTelemetry();

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

The following code helps to send SMS over the global network using ASP.Net Core.

[HttpPost]
        public IActionResult Registration(RegistrationViewModel model)
        {
            ViewData["Message"] = "Your registration page!.";

            ViewBag.SuccessMessage = null;

            if (model.Email.Contains("menoth.com"))
            {
                ModelState.AddModelError("Email", "We don't support menoth Address !!");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    // Find your Account Sid and Auth Token at twilio.com/user/account
                    const string accountSid = "AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
                    const string authToken = "6XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
                    TwilioClient.Init(accountSid, authToken);

                    var to = new PhoneNumber("+91" + model.Mobile);
                    var message = MessageResource.Create(
                        to,
                        from: new PhoneNumber("+18XXXXXXXXXX"), //  From number, must be an SMS-enabled Twilio number ( This will send sms from ur "To" numbers ).
                        body:  $"Hello {model.Name} !! Welcome to Asp.Net Core With Twilio SMS API !!");

                    ModelState.Clear();
                    ViewBag.SuccessMessage = "Registered Successfully !!";
                }
                catch (Exception ex)
                {
                    Console.WriteLine($" Registration Failure : {ex.Message} ");
                }

            }

            return View();
        }

New Tag Helpers

We use the latest ASP.NET Core tag helpers on the registration page to access the controller and actions, validation, etc.

<div asp-validation-summary="All" class="text-danger"></div>   
<label asp-for="Name"></label>  
<input asp-for="Name" class="form-control" />  
<span asp-validation-for="Name" class="text-danger"></span>  
<a asp-controller="Home" asp-action="Home" class="btn btn-info">Cancel</a>

Inject Tag Helpers

In the way given below, we can inject the tag helpers in our application. Now, create the default “_ViewImports.cshtml” file in the View Folder and add the code given below in that file.

@addTagHelper "*,Microsoft.AspNetCore.Mvc.TagHelpers"

Client Side Validations

The Client Side validation is done with the help of Bootstrap and jQuery.

Image title

Registration Page

The message will send to the respective mobile number that you have given in the mobile number column on the registration page.

Image title

OutPut

We will get an SMS from the Twilio account, once we have registered successfully.

Image title

References:

  • Twilio API Docs

  • Twilio SMS

  • Tech Blog

Download the source code here.

You can download other ASP.NET Core source code from MSDN Code, using the link below:

  • MSDN Gallery Samples

We learned how to Send SMS using ASP.NET Core With Twilio SMS API. I hope this article is useful for all ASP.NET Core beginners.

SMS ASP.NET ASP.NET Core API

Published at DZone with permission of Rajeesh Menoth, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core
  • Revolutionizing Content Management
  • Revolutionizing API Development: A Journey Through Clean Architecture With Adapter Pattern in ASP.NET Core

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!