Sending SMS Using ASP.NET Core With Twilio SMS API

Introduction
 
In this article, we will explain how to Send SMS using ASP.NET Core With Twilio SMS API. Twilio provides third party SMS API for sending sms over the global network. So we can learn a little bit through this article.
 
Before reading this article, you must read the articles given below for ASP.NET Core knowledge. 
Package Installation
  • Install-Package Twilio -Version 5.9.1
    This package will install all the sms,video,etc related classes,methods and API’s for twilio.

  • Install-Package jQuery.Validation.Unobtrusive -Version 2.0.20710
    This package will install all the bootstrap & validation related Jquery libraries in our project.
Important Notes
  1.  If you don’t have any twilio account then you should register a free account using the following link Click here & I choose language as "C#".

  2. Once registration is completed then we can access Dashboard and Console of our twilio account. We will get "Account SID & Auth Token Id" from Dashboard for sending sms.



  3. 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 ur “To” numbers ). Go to this link click here and Click on the “Get a number” button in the “Programmble SMS Menu” mentioned in the following screenshot.



  4. You have to get $15 for sending sms In the 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 are providing "ASP.Net Core MVC" & "Twilio SMS API" Classes & Methods.
  1. using System;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using RegistrationForm.ViewModels;  
  4. using Twilio;  
  5. using Twilio.Types;  
  6. 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 Startup.cs Class. The code given below clearly mentions that manually we need to add our controller name and an action name in "MapRoute". We can change this controller name and action name, which is based on our requirement in the Applications.
  1. app.UseMvc(routes =>  
  2.            {  
  3.                routes.MapRoute(  
  4.                    name: "default",  
  5.                    template: "{controller=Home}/{action=Index}/{id?}");  
  6.            });  
Startup.cs
 
The class given below contains the complete middleware details in our Applications. I choose a default project in our Visual Studio 2015. So automatically it will generate the following classes & methods.
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.Configuration;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5. using Microsoft.Extensions.Logging;  
  6.    
  7. namespace SMSApp  
  8. {  
  9.     public class Startup  
  10.     {  
  11.         public Startup(IHostingEnvironment env)  
  12.         {  
  13.             var builder = new ConfigurationBuilder()  
  14.                 .SetBasePath(env.ContentRootPath)  
  15.                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)  
  16.                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)  
  17.                 .AddEnvironmentVariables();  
  18.    
  19.             if (env.IsDevelopment())  
  20.             {  
  21.                 // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.  
  22.                 builder.AddApplicationInsightsSettings(developerMode: true);  
  23.             }  
  24.             Configuration = builder.Build();  
  25.         }  
  26.    
  27.         public IConfigurationRoot Configuration { get; }  
  28.    
  29.         // This method gets called by the runtime. Use this method to add services to the container.  
  30.         public void ConfigureServices(IServiceCollection services)  
  31.         {  
  32.             // Add framework services.  
  33.             services.AddApplicationInsightsTelemetry(Configuration);  
  34.    
  35.             services.AddMvc();  
  36.         }  
  37.    
  38.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  39.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  40.         {  
  41.             loggerFactory.AddConsole(Configuration.GetSection("Logging"));  
  42.             loggerFactory.AddDebug();  
  43.    
  44.             app.UseApplicationInsightsRequestTelemetry();  
  45.    
  46.             if (env.IsDevelopment())  
  47.             {  
  48.                 app.UseDeveloperExceptionPage();  
  49.                 app.UseBrowserLink();  
  50.             }  
  51.             else  
  52.             {  
  53.                 app.UseExceptionHandler("/Home/Error");  
  54.             }  
  55.    
  56.             app.UseApplicationInsightsExceptionTelemetry();  
  57.    
  58.             app.UseStaticFiles();  
  59.    
  60.             app.UseMvc(routes =>  
  61.             {  
  62.                 routes.MapRoute(  
  63.                     name: "default",  
  64.                     template: "{controller=Home}/{action=Index}/{id?}");  
  65.             });  
  66.         }  
  67.     }  
  68. }  
Code
 
The following code help to send sms over the global network using ASP.Net Core With Twilio SMS API.
  1. [HttpPost]  
  2.         public IActionResult Registration(RegistrationViewModel model)  
  3.         {  
  4.             ViewData["Message"] = "Your registration page!.";  
  5.    
  6.             ViewBag.SuccessMessage = null;  
  7.    
  8.             if (model.Email.Contains("menoth.com"))  
  9.             {  
  10.                 ModelState.AddModelError("Email""We don't support menoth Address !!");  
  11.             }  
  12.    
  13.             if (ModelState.IsValid)  
  14.             {  
  15.                 try  
  16.                 {  
  17.                     // Find your Account Sid and Auth Token at twilio.com/user/account  
  18.                     const string accountSid = "AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";  
  19.                     const string authToken = "6XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";  
  20.                     TwilioClient.Init(accountSid, authToken);  
  21.    
  22.                     var to = new PhoneNumber("+91" + model.Mobile);  
  23.                     var message = MessageResource.Create(  
  24.                         to,  
  25.                         from: new PhoneNumber("+18XXXXXXXXXX"), //  From number, must be an SMS-enabled Twilio number ( This will send sms from ur "To" numbers ).  
  26.                         body:  $"Hello {model.Name} !! Welcome to Asp.Net Core With Twilio SMS API !!");  
  27.    
  28.                     ModelState.Clear();  
  29.                     ViewBag.SuccessMessage = "Registered Successfully !!";  
  30.                 }  
  31.                 catch (Exception ex)  
  32.                 {  
  33.                     Console.WriteLine($" Registration Failure : {ex.Message} ");  
  34.                 }  
  35.    
  36.             }  
  37.    
  38.             return View();  
  39.         }  
New Tag Helpers
 
We used latest ASP.NET Core Tag Helpers in Registration page to access controller and actions, validation etc.
  1. <div asp-validation-summary="All" class="text-danger"></div>  
  2.    
  3. <label asp-for="Name"></label>    
  4. <input asp-for="Name" class="form-control" />    
  5. <span asp-validation-for="Name" class="text-danger"></span>    
  6. <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 View Folder and add the code given below in that file.
  1. @addTagHelper "*,Microsoft.AspNetCore.Mvc.TagHelpers"  
Client Side validations
 
The Client Side validation is done with the help of Bootstrap & jQuery etc.
 
 
 
Registration Pge
 
The message will send to the respective mobile number that you have given in the mobile number column in registration page.
 


OutPut
 
We will get a sms from the Twilio account, once we have registered successfully.
 
 
 
Reference
Download
See Also
 
You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.
Summary
 
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.