Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. Send SMS using Twillio in Asp.Net

Send SMS using Twillio in Asp.Net

Date- Aug 27,2022 Updated Mar 2026 8399 Free Download Pay & Download
Twillio Twillio in AspNet

Prerequisites

Before we dive into the implementation, there are a few prerequisites you need to have in place:

  • Twilio Account: Sign up for a Twilio account if you haven't already. You'll need access to your Account SID and Auth Token from the Twilio dashboard.
  • ASP.NET Core Development Environment: Ensure you have the .NET SDK installed on your machine. You can download it from the official Microsoft .NET website.
  • Basic Knowledge of ASP.NET Core: Familiarity with ASP.NET Core MVC and dependency injection will be helpful.

Installing the Twilio NuGet Package

To get started, the first step is to install the Twilio NuGet package in your ASP.NET Core project. This package contains all the necessary libraries to interact with the Twilio API.

dotnet add package Twilio

After installing the Twilio package, you will need to modify the appsettings.json file with your Twilio credentials. This is how your configuration should look:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Twilio": {
    "AccountSid": "YOUR_ACCOUNT_SID",
    "AuthToken": "YOUR_AUTH_TOKEN"
  }
}
Send SMS using Twillio in AspNet

Creating a Twilio Client

Next, we will create a TwilioClient class to encapsulate the functionality for sending SMS messages. This class will implement the ITwilioRestClient interface, allowing us to customize the underlying HTTP client.

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

namespace Twilio.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;
  }
} 

After creating the client, we need to register it within the Startup.cs file to enable dependency injection.

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

Sending an SMS

Now that we have our Twilio client set up, we can create an API that allows us to send SMS messages. We will define a model called SmsMessage to represent the data we need to send.

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

Next, we will create an API controller called SmsController to handle incoming requests.

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

namespace Twilio.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
      );
      return Ok("Success: " + message.Sid);
    }
  }
}
Send SMS using Twillio in AspNet 2

Testing the SMS Functionality

To test the SMS functionality, you can use tools like Postman or cURL. Here's how to send a test request using Postman:

  1. Change the HTTP Method from GET to POST.
  2. Set the request URL to http://localhost:7029/api/send-sms (or the appropriate URL for your application).
  3. Click on Body, choose raw, and change the Content-Type to JSON (application/json).
  4. Enter a JSON request with the following structure:
{
  "to": "+919034589555",
  "from": "+18454098435",
  "message": "Hey Code2night Testing Message from Twilio :)"
}

Ensure that the from parameter is set to your Twilio phone number, and the to parameter is a phone number that can receive SMS messages.

Edge Cases & Gotchas

When working with SMS messaging, there are several edge cases and potential issues to consider:

  • Rate Limits: Twilio imposes rate limits on the number of SMS messages you can send. Ensure you handle HTTP 429 Too Many Requests responses gracefully.
  • Invalid Phone Numbers: If you attempt to send a message to an invalid phone number, Twilio will return an error. Validate phone numbers before sending messages.
  • Message Length: SMS messages have a character limit (typically 160 characters for standard SMS). If your message exceeds this limit, it may be split into multiple messages. Be mindful of this when crafting your messages.

Performance & Best Practices

To ensure optimal performance when sending SMS messages, consider the following best practices:

  • Asynchronous Processing: Use asynchronous methods to send SMS messages to avoid blocking the main thread. This can improve the responsiveness of your application.
  • Batch Sending: If you need to send a large number of messages, consider batching them to reduce API calls and improve efficiency.
  • Error Handling: Implement robust error handling to manage potential failures in sending messages. Log errors and provide user feedback if necessary.
  • Security: Keep your Twilio credentials secure. Avoid hardcoding sensitive information in your code and consider using environment variables or secure vaults.

Conclusion

Integrating SMS functionality into your ASP.NET application using Twilio can significantly enhance communication with users. By following the steps outlined in this article, you can easily send SMS messages from your application.

  • Install the Twilio NuGet package and configure your application settings.
  • Create a Twilio client and an API controller to manage SMS requests.
  • Test your implementation using tools like Postman.
  • Be aware of edge cases, rate limits, and best practices for optimal performance.

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Send SMS using Twillio in Asp.Net MVC
Oct 13, 2022
How to make Voice Call using Twillio in Asp.Net MVC
Jan 29, 2024
Get SMS Logs from Twillio in Asp.Net MVC
Oct 17, 2022
Previous in ASP.NET Core
HTTP Error 500.31 Failed to load ASP NET Core runtime
Next in ASP.NET Core
Reading Values From Appsettings.json In ASP.NET Core
Buy me a pizza

Comments

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 26038 views
  • Exception Handling Asp.Net Core 20781 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20259 views
  • How to implement Paypal in Asp.Net Core 19658 views
  • Task Scheduler in Asp.Net core 17561 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
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 | 1770
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
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor