Code2night
  • Home
  • Blogs
  • Tutorial
  • Post Blog
  • Tools
    • Json Beautifier
    • Html Beautifier
  • Members
    • Register
    • Login
  1. Home
  2. Blogpost
27 Aug
2022

Send SMS using Twillio in Asp.Net

by Shubham Batra

1508

Download Attachment

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.

  • |
  • Twilio SMS and ASPNET Core 60 , How to Send an SMS with ASPNET Core , Using Dependency Injection with Twilio SMS and ASPNET Core 21 , Twillio , Twillio in AspNet , Twillio SMS Integration

Comments

Follow Us On Social Media - Like Us On Facebook

Best Sellers

product 1

Hand Hug Bracelet For Women Men Cuff Bangle Adjustable Lover Couple Bracelets

Can be given as a gift to your family, relatives, or friends

Buy $15.99
product 1

Teddy bear hug bear plush toy bear cub

Can be given as a gift to your family, relatives, or friends


Buy $49.99

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
Thank you for Downloading....!

Subscribe for more tutorials

Support our team

Continue with Downloading

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 © 2023 by Code2night. All Rights Reserved

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