Back to: ASP.NET Core Identity Tutorials
How to Configure SMS Service in ASP.NET Core
In this article, I will explain how to configure SMS Service in ASP.NET Core. Please read our previous article discussing how to implement CAPTCHA in ASP.NET Core.
What is an SMS Service?
An SMS (Short Message Service) service is a platform or functionality that enables the sending of short text messages between devices via cellular networks. In the context of web applications, an SMS service allows applications to communicate with users via text messages, facilitating functionalities such as notifications, alerts, Two-Factor Authentication (2FA), marketing campaigns, and more.
SMS services are typically provided by third-party SMS gateway providers (e.g., Twilio, Nexmo, Plivo) that offer APIs for integration. These APIs allow developers to send messages in their applications programmatically. The SMS service typically connects your application with an SMS gateway (such as Twilio, Nexmo, or others), which handles the actual delivery of messages to the mobile networks.
Why Do We Need SMS Service in Web Applications?
Web applications often require real-time communication with users. SMS services are an effective way to communicate with users who may not have internet access or prefer to receive notifications via text. Typical scenarios for integrating SMS services in web applications include:
- User Verification & Authentication: Send SMS-based one-time passcodes (OTP) for two-factor authentication (2FA) or account verification.
- Notifications: Alert users about important events, such as order status updates, delivery notifications, or account activity.
- Marketing and Promotions: Send personalized promotional offers, discounts, or product updates directly to users’ mobile phones.
- Password Recovery: Allow users to reset their passwords by sending recovery links or codes via SMS.
Integrating SMS services into web applications enhances user engagement and improves security by enabling seamless, real-time communication.
How to Configure SMS Service with ASP.NET Core?
Configuring an SMS service in an ASP.NET Core application involves integrating with an SMS gateway provider that provides APIs for sending SMS messages. Let us understand how to set up an SMS service in ASP.NET Core:
Choose an SMS Gateway Provider
Before integrating SMS functionalities, select a reliable SMS gateway provider that aligns with your specific requirements. Twilio is a popular choice due to its comprehensive APIs, global reach, and extensive documentation. Other reputable providers include Nexmo (Vonage), Plivo, and SendGrid. For this example, we will use Twilio.
Set Up an Account and Obtain API Credentials
Create an account with your chosen SMS gateway provider. Complete any necessary verification steps, such as phone number verification or business validation, as required. After setting up your account, retrieve your API credentials (e.g., API Key, Auth Token). These credentials are essential for authenticating API requests from your application.
Install NuGet Package
Depending on the provider, you may need to install their official SDK or relevant NuGet package. For Twilio, you need to install the Twilio NuGet package for ASP.NET Core. You can install it via the Visual Studio Package Manager Console: Install-Package Twilio
Setting up a Twilio SMS Account
The first step is to create a Twilio account. When we create an account, we will be given a Free Trial Account with a value of $ 15.50 USD. You can use the trial balance toward purchasing a Phone Number for sending messages. Setting up a Twilio SMS account involves several steps. Let us proceed and understand this step by step:
Sign Up for Twilio:
To use Twilio for SMS, you will need to create an account:
- Visit the Twilio website: https://www.twilio.com/
- Click on the “Sign Up” button.
- Fill in your details like First Name, Last Name, Email, and Password.
- Verify your email address to complete the sign-up process.
Phone Number Verification:
After signing up, Twilio requires you to verify your personal phone number as a security measure:
- Enter your phone number, and Twilio will send a verification code via SMS or a call.
- Enter the code to complete the verification process.
- Save the recovery code in case you lose access to your phone or verification device.
Account Activation:
- You may need to provide additional information about how you plan to use Twilio services to activate your account fully.
Choosing a Twilio Phone Number:
Once your account is activated, you can choose a Twilio phone number. This number will be used for sending SMS messages. To do so, select a phone number based on your preferred country and its features, as shown in the image below.
Once you have selected and purchased a phone number, you will see the following details in your Twilio account:
- Account SID
- Auth Token
- Twilio Phone Number
Copy these values as you will need them when integrating Twilio with your ASP.NET Core application. The dashboard page should look as shown in the image below.
Adding Test Phone Numbers:
On a Twilio trial account, you can only send SMS messages to verified phone numbers. You can add multiple verified numbers in the Twilio console. Please follow the screen below for a better understanding.
Twilio API Integration:
Now that we have our Twilio account and phone number, it’s time to integrate the Twilio API into our ASP.NET Core application. Twilio provides comprehensive documentation and SDKs for different programming languages, including C#.
Adding Twilio Package:
Open the Package Manager Console and then execute the following command, which will install the Twilio NuGet Package for ASP.NET Core.
- Install-Package Twilio
Configure Twilio Settings:
In the appsettings.json file, store your Twilio credentials (Account SID, Auth Token, and Twilio Phone Number). This allows you to keep sensitive information out of your codebase, making it easier to configure your application for different environments.
"SMSSettings": { "AccountSID": "Your Account SID", "AuthToken": "Your Account Auth Token", "FromNumber": "Your Twilio Number" }
Creating SMS Sending Service:
Next, we will create a service class in our ASP.NET Core application to encapsulate the SMS sending logic. So, create an interface named ISMSSender.cs within the Services folder and then copy and paste the following code.
namespace ASPNETCoreIdentityDemo.Services { public interface ISMSSender { Task<bool> SendSmsAsync(string toPhoneNumber, string message); } }
Implementing SMS Sender Service:
Create a class file named SMSSender.cs within the Services folder and then copy and paste the following code.
using Twilio.Types; using Twilio; using Twilio.Rest.Api.V2010.Account; namespace ASPNETCoreIdentityDemo.Services { public class SMSSender : ISMSSender { // To access configuration settings from appsettings.json. private readonly IConfiguration _configuration; // Variables to store Twilio account credentials and the sender's phone number private readonly string? AccountSID; private readonly string? AuthToken; private readonly string? FromNumber; public SMSSender(IConfiguration configuration) { _configuration = configuration; // Retrieve Twilio Account SID, Auth Token, and FromNumber from appsettings.json. AccountSID = _configuration["SMSSettings:AccountSID"]; AuthToken = _configuration["SMSSettings:AuthToken"]; FromNumber = _configuration["SMSSettings:FromNumber"]; } // Asynchronous method to send an SMS message. public async Task<bool> SendSmsAsync(string toPhoneNumber, string message) { try { // Validate input parameters to ensure toPhoneNumber and message are not empty. if (string.IsNullOrEmpty(toPhoneNumber) || string.IsNullOrEmpty(message)) { // Return false if invalid. return false; } // Check if Twilio credentials are missing, and throw an exception if so. if (string.IsNullOrEmpty(AccountSID) || string.IsNullOrEmpty(AuthToken) || string.IsNullOrEmpty(FromNumber)) { throw new ArgumentException("Twilio Account SID, Auth Token, and FromNumber must be provided in the configuration."); } //Please check + symbol before the Phone Number which is required by Twilio if (!toPhoneNumber.StartsWith("+")) { toPhoneNumber = "+" + toPhoneNumber; } // Initialize the Twilio client with the provided AccountSID and AuthToken for authentication. TwilioClient.Init(AccountSID, AuthToken); // Create a new instance of CreateMessageOptions to configure the SMS details. // Set the recipient phone number. var messageOptions = new CreateMessageOptions(new PhoneNumber(toPhoneNumber)) { // Set the sender phone number (from the configuration). From = new PhoneNumber(FromNumber), // Set the body content of the message. Body = message }; // Use the Twilio API to send the SMS asynchronously. var msg = await MessageResource.CreateAsync(messageOptions); // If the SMS is successfully sent, return true. return true; } catch (Exception) { // Handle any exceptions (e.g., network issues, Twilio errors) and return false. return false; } } } }
Registering the SMSSender Service:
Next, we need to register the SMSSender Service with the built-in dependency injection container. To do so, please add the following code to the Main method of the Program class. This registers the SMSSender class so that it can be injected into controllers or other services within your application.
builder.Services.AddSingleton<ISMSSender, SMSSender>();
Why is Singleton Service ideal here?
- Stateless service: Your SMSSender holds no per-request state and only reads configuration. Such “pure” utility services are best as singletons to avoid needless allocations.
- External client reuse: Creating/re-initializing the Twilio client state per call isn’t useful. A singleton lets you build the client once and reuse it efficiently.
- No scoped deps: It doesn’t depend on scoped services like DbContext, so singleton is safe.
With this, we integrate SMS functionality into our ASP.NET Core application using Twilio. This setup can be easily extended to other SMS providers by modifying the integration details according to the provider’s API documentation.
In the next article, I will discuss how to add and Verify Phone Numbers in ASP.NET Core Identity. In this article, I explain how to integrate SMS Service with ASP.NET Core. I hope you enjoy this article on integrating the SMS Service in ASP.NET Core.
Registration Open – Full-Stack .NET with Angular & ASP.NET Core
Session Time: 8:30 PM – 10:00 PM IST
Advance your career with our expert-led, hands-on live training program. Get complete course details, the syllabus, and Zoom credentials for demo sessions via the links below.