- 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#".
- 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.
- 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.
- 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.
- 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 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.
- app.UseMvc(routes =>
- {
- routes.MapRoute(
- name: "default",
- template: "{controller=Home}/{action=Index}/{id?}");
- });
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.
- 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())
- {
-
- builder.AddApplicationInsightsSettings(developerMode: true);
- }
- Configuration = builder.Build();
- }
-
- public IConfigurationRoot Configuration { get; }
-
-
- public void ConfigureServices(IServiceCollection services)
- {
-
- services.AddApplicationInsightsTelemetry(Configuration);
-
- services.AddMvc();
- }
-
-
- 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?}");
- });
- }
- }
- }
Code
The following code help to send sms over the global network using ASP.Net Core With Twilio SMS API.
- [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
- {
-
- 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"),
- 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 used latest ASP.NET Core Tag Helpers in Registration page to access 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 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 & 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.