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 Account Lockout in ASP.NET Core Identity.
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 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.
For applications, 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 programmatically send SMS messages in their applications. 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 might not have internet access or prefer receiving notifications via text. Common 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, delivery updates, 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.
In summary, integrating SMS services in 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 offers robust APIs for sending SMS messages. The following is a step-by-step guide on how to set up an SMS service, specifically with Twilio (one of the leading SMS gateway providers) in ASP.NET Core:
Choose an SMS Gateway Provider
Before integrating SMS functionalities, you need to select a reliable SMS gateway provider that aligns with your 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. After account setup, retrieve your API credentials (e.g., API Key, Auth Token). These credentials are essential for authenticating API requests from your application. For Twilio, you will receive an Account SID and an Auth Token that will be used for authentication in your application.
Install Necessary Packages
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 Package Manager Console: Install-Package Twilio
Setting up a Twilio SMS Account
The first thing we need to do is create a Twilio account. When we create an account, we are going to be given a free trial account with 15.50 USD. We can use the trial balance toward purchasing a phone number and sending and receiving 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 fully activate your account.
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 below image.
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 below image.
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 below screen for a better understanding.
Twilio API Integration in ASP.NET Core for SMS Service:
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 execute the following command to 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 and makes 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 in ASP.NET Core:
Next, we will create a service class in your ASP.NET Core application to encapsulate the SMS-sending logic. So, create a class file with the named SMSSender.cs within the Services folder and copy and paste the following code. The following code is self-explained, so please read the comment lines for a better understanding.
using Twilio.Types; using Twilio; using Twilio.Rest.Api.V2010.Account; namespace ASPNETCoreIdentityDemo.Services { public class SMSSender { // 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 'to' and 'message' are not empty. // Return false if invalid. if (string.IsNullOrEmpty(toPhoneNumber) || string.IsNullOrEmpty(message)) { return false; } // Check if Twilio credentials are missing, and throw an exception if so. if (string.IsNullOrEmpty(AccountSID) || string.IsNullOrEmpty(AuthToken)) { throw new ArgumentException("Twilio Account SID and Auth Token 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. var messageOptions = new CreateMessageOptions(new PhoneNumber(toPhoneNumber)) // Set the recipient phone number. { From = new PhoneNumber(FromNumber), // Set the sender phone number (from the configuration). Body = message // Set the body content of the 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 in Program Class:
Next, we need to register the SMSSender Service to 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.AddTransient<SMSSender>();
Following these steps, we can 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 SMS service in the ASP.NET Core.