Send SMS using Twillio in Asp.Net | Code2night.com
Code2night
  • Home
  • Blogs
  • Guest Posts
  • Tutorial
  • Post Blog
  • Register
  • Login
  1. Home
  2. Blogpost

Send SMS using Twillio in Asp.Net

Date- Aug 27,2022

6284

Free Download Pay & Download
Twillio Twillio in AspNet

Installing the Twilio NuGet package

 dotnet add package Twilio

After installing the Twilio package, we are going to modify appsettings.json with the account SID and the auth token found from the Twilio dashboard

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Twilio": {
    "AccountSid": "AC3a936dd92e86s15cf74fedb0ecd6dsf37199",
    "AuthToken": "52b86fa7sdd9c19b4b18bf5b370411s0sddc26"
  }
}

Let’s create a folder called Services and create the TwilioClient class:

 using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Twilio.Clients;
using Twilio.Http;

namespace Twillio.Services
{
    public class TwilioClient : ITwilioRestClient
    {
        private readonly ITwilioRestClient _innerClient;
        public TwilioClient(IConfiguration config, System.Net.Http.HttpClient httpClient)
        {
            // customize the underlying HttpClient
            httpClient.DefaultRequestHeaders.Add("X-Custom-Header", "CustomTwilioRestClient-Demo");
            _innerClient = new TwilioRestClient(
                config["Twilio:AccountSid"],
                config["Twilio:AuthToken"],
                httpClient: new SystemNetHttpClient(httpClient));
        }
        public Response Request(Request request) => _innerClient.Request(request);
        public Task<Response> RequestAsync(Request request) => _innerClient.RequestAsync(request);
        public string AccountSid => _innerClient.AccountSid;
        public string Region => _innerClient.Region;
        public Twilio.Http.HttpClient HttpClient => _innerClient.HttpClient;
    }
}

Now that we finished our client, let’s register it in Startup.cs so we can use it via dependency injection. Let’s modify the ConfigureServices methods within the Startup class:

builder.Services.AddControllers();

builder.Services.AddHttpClient< ITwilioRestClient, TwilioClient>();

Sending an SMS The next part of this project is to create an API that will allow us to send a text message to a phone number. First, we are going to need to define the SmsMessage model within a Models folder:

    public class SmsMessage
    {
        public string To { get; set; }
        public string From { get; set; }
        public string Message { get; set; }
    }

The next part of our application is the API controller that will receive our requests. Let’s create the SmsController class within a Controllers folder:

 using Microsoft.AspNetCore.Mvc;
using Twilio.Clients;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
using Twillio.Models;

namespace Twillio.Controllers
{
    [ApiController]
    public class SmsController : ControllerBase
    {
        private readonly ITwilioRestClient _client;
        public SmsController(ITwilioRestClient client)
        {
            _client = client;
        }

        [HttpPost("api/send-sms")]
        public IActionResult SendSms(SmsMessage model)
        {
            var message = MessageResource.Create(
                to: new PhoneNumber(model.To),
                from: new PhoneNumber(model.From),
                body: model.Message,
                client: _client); // pass in the custom client
            return Ok("Success" + message.Sid);
        }
    }
}

  • Change the HTTP Method from GET to POST
  • Set the request URL to http://localhost:7029/api/send-sms (or whichever URL your app is running at)
  • Click Body, choose raw, and change the Content-Type from Text to JSON(application/json)
  • Enter a JSON request, like the one below, containing to, from, and body, parameters
  • Replace the value for the from parameter with your Twilio phone number
  • The value for the to a parameter must be a phone number you’ve registered with Twilio, typically the number you used when creating your account, and it must be able to receive SMS
{
    "to": "+919034589555",
    "from": "+18454098435",
    "message": "Hey Code2night Testing Message from Twilio :)"
}

f

So, this is how we can integrate Twillio in Asp.net  and send sms using Twillio in Asp.net.

Comments

Tags

LinkedinLogin
LinkedinProfile
GetLinkedinProfile
C#
Aspnet
MVC
Linkedin
ITextSharp
Export to Pdf
AspNet Core
AspNet
View to Pdf in Aspnet
Model Validation In ASPNET Core MVC 60
Model Validation
Model Validation In ASPNET Core MVC
Model Validation In ASPNET
Image Compression in AspNet
Compress Image in c#
AspNet MVC
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1190
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp Join Us On Facebook

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Panipat
  • info@Code2night.com

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2025 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Terms & Conditions
  • Refund Policy
  • About Us
  • Privacy Policy
  • Json Beautifier
  • Guest Posts