Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • 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. Integrating MSG91 for OTP and SMS in ASP.NET Core Applications

Integrating MSG91 for OTP and SMS in ASP.NET Core Applications

Date- Apr 28,2026 99
aspnetcore msg91

Overview

In the digital age, securing user accounts is paramount. One of the most effective methods for achieving this is through the use of One-Time Passwords (OTPs). An OTP is a unique code that is valid for a single transaction or login session, providing an additional layer of security beyond traditional passwords. MSG91 is a widely used service in India that facilitates SMS sending, including OTPs, to users' mobile devices. By integrating MSG91 into your ASP.NET Core application, you can streamline the process of user verification and enhance security.

MSG91 exists to solve the problem of user authentication and communication in a reliable and scalable manner. The service offers a robust API that allows developers to send OTPs and SMS messages efficiently. Real-world use cases include banking applications, e-commerce platforms, and any service requiring secure user verification. This integration not only improves security but also enhances user experience by providing instant communication.

Prerequisites

  • ASP.NET Core: Familiarity with ASP.NET Core framework and creating web applications.
  • REST API Knowledge: Understanding of how to make HTTP requests and handle responses.
  • MSG91 Account: You need an MSG91 account to access the API key and other configurations.
  • NuGet Package Manager: Ability to install required NuGet packages in your ASP.NET Core project.

Setting Up MSG91 Account

Before integrating MSG91 into your ASP.NET Core application, you must set up your MSG91 account. This involves registering on the MSG91 website, verifying your phone number, and obtaining your API key. The API key is essential as it authenticates your requests to the MSG91 service.

Once registered, navigate to the dashboard where you can find your API key. Be sure to save this in a secure location, as it will be required in your application to authenticate API calls. Additionally, you may need to configure your sender ID, which is the name that will appear on users' mobile devices when they receive an SMS.

Integrating MSG91 API in ASP.NET Core

To integrate MSG91 into your ASP.NET Core application, you will primarily use the HttpClient class to send HTTP requests to the MSG91 API. This involves creating a service that encapsulates the logic for sending OTPs and SMS messages. Below is an example of how to set up this integration:

using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

public class Msg91Service
{
    private readonly HttpClient _httpClient;
    private readonly string _apiKey;
    private readonly string _senderId;

    public Msg91Service(string apiKey, string senderId)
    {
        _httpClient = new HttpClient();
        _apiKey = apiKey;
        _senderId = senderId;
    }

    public async Task SendOtpAsync(string mobileNumber, string otp)
    {
        var url = $"https://api.msg91.com/api/sendotp?mobile={mobileNumber}&otp={otp}&authkey={_apiKey}&sender={_senderId}&message=Your OTP is {otp}"
        var response = await _httpClient.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            return "OTP sent successfully";
        }
        else
        {
            return "Failed to send OTP";
        }
    }
}

This code defines a Msg91Service class that encapsulates the logic for sending OTPs. The constructor accepts the API key and sender ID, which are stored for use in the SendOtpAsync method. This method constructs the URL for the API request, including the mobile number, OTP, API key, and sender ID. An HTTP GET request is made to the MSG91 API, and the response is checked for success.

The expected output of the SendOtpAsync method is a success message if the OTP is sent successfully. In a production application, you would likely want to handle errors and exceptions more gracefully.

Sending SMS Messages

In addition to sending OTPs, you may also want to send regular SMS messages. The process is similar to sending OTPs, but the API endpoint and parameters differ slightly. Here’s how you can extend the Msg91Service to include a method for sending SMS:

public async Task SendSmsAsync(string mobileNumber, string message)
{
    var url = $"https://api.msg91.com/api/sendhttp.php?authkey={_apiKey}&mobiles={mobileNumber}&message={message}&sender={_senderId}&route=4";
    var response = await _httpClient.GetAsync(url);

    if (response.IsSuccessStatusCode)
    {
        return "SMS sent successfully";
    }
    else
    {
        return "Failed to send SMS";
    }
}

This method constructs a URL for sending an SMS and makes an HTTP GET request. Similar to the OTP method, it checks the response and returns an appropriate message.

Testing the MSG91 Integration

To ensure that your integration works correctly, you should write unit tests for the Msg91Service. Using a mocking framework like Moq can help you simulate HTTP responses without actually calling the MSG91 API. Here’s how you can write a test for the SendOtpAsync method:

using Moq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

public class Msg91ServiceTests
{
    [Fact]
    public async Task SendOtpAsync_ShouldReturnSuccess_WhenResponseIsSuccessful()
    {
        // Arrange
        var mockHttp = new Mock();
        mockHttp.Protected()
            .Setup>("SendAsync", 
                It.IsAny(), It.IsAny())
            .ReturnsAsync(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
            });

        var httpClient = new HttpClient(mockHttp.Object);
        var msg91Service = new Msg91Service("your_api_key", "your_sender_id");

        // Act
        var result = await msg91Service.SendOtpAsync("1234567890", "123456");

        // Assert
        Assert.Equal("OTP sent successfully", result);
    }
}

This test checks that when the SendOtpAsync method is called, it returns a success message if the response from the mocked HTTP client is successful. You can extend this test suite to cover edge cases and error scenarios as well.

Edge Cases & Gotchas

While integrating with external APIs like MSG91, there are several edge cases and pitfalls to be aware of. One common issue is rate limiting. MSG91 has limits on how many messages can be sent within a certain time frame. If you exceed this limit, you may receive an error response. Always check the documentation for the latest rate limits.

Another potential issue is the formatting of the mobile number. Ensure that the mobile numbers you send are correctly formatted, including country codes, to avoid failures in sending messages. Additionally, be cautious with the handling of sensitive data such as API keys. Never hard-code them in your source code; use environment variables or configuration files instead.

Performance & Best Practices

When integrating with external services, performance is crucial. One best practice is to implement asynchronous calls, as demonstrated in the examples above. This prevents blocking the main thread and ensures that your application remains responsive, especially when sending multiple messages.

Another important aspect is error handling. Implement retry logic for transient errors, such as network issues. Consider using libraries like Polly for resilient HTTP calls. Monitor your application for performance metrics and error rates to identify any bottlenecks in the integration.

Real-World Scenario: User Registration with OTP Verification

Let’s tie everything together in a realistic mini-project. Imagine you are developing a user registration feature that requires OTP verification. Here’s how you can implement this:

public class UserRegistrationController : Controller
{
    private readonly Msg91Service _msg91Service;

    public UserRegistrationController(Msg91Service msg91Service)
    {
        _msg91Service = msg91Service;
    }

    [HttpPost]
    public async Task Register(UserRegistrationModel model)
    {
        if (ModelState.IsValid)
        {
            var otp = GenerateOtp();
            await _msg91Service.SendOtpAsync(model.MobileNumber, otp);
            return Ok("OTP sent to your mobile number.");
        }
        return BadRequest(ModelState);
    }

    private string GenerateOtp()
    {
        var random = new Random();
        return random.Next(100000, 999999).ToString();
    }
}

This UserRegistrationController handles user registration. When a user submits their registration, a random OTP is generated and sent to their mobile number using the Msg91Service. This provides a seamless registration experience with added security.

Conclusion

  • MSG91 provides a robust solution for sending OTPs and SMS in ASP.NET Core applications.
  • Proper setup of the MSG91 account and understanding of the API is essential for successful integration.
  • Testing and handling edge cases are critical for a reliable application.
  • Implementing performance best practices ensures a responsive user experience.
  • Real-world scenarios demonstrate the practical application of OTP in user registration.

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

Related Articles

Integrating Twitter X OAuth 2.0 in ASP.NET Core: A Comprehensive Guide
Apr 30, 2026
Integrating Google OAuth 2.0 Login in ASP.NET Core: A Comprehensive Guide
Apr 29, 2026
Integrating LinkedIn OAuth in ASP.NET Core for Professional Login
May 01, 2026
Implementing GitHub OAuth Integration in ASP.NET Core for Seamless User Login
Apr 30, 2026
Previous in ASP.NET Core
Integrating Vonage Nexmo SMS API in ASP.NET Core Applications
Next in ASP.NET Core
Integrating Fast2SMS with ASP.NET Core for Reliable SMS Delivery …
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    Complete Guide to C++ Classes: Explained with Examples 4,212 views
  • 2
    Implementing an End-to-End CI/CD Pipeline for ASP.NET Core… 368 views
  • 3
    Create Database and CRUD operation 3,388 views
  • 4
    Mastering TypeScript Utility Types: Partial, Required, Rea… 675 views
  • 5
    Responsive Slick Slider 23,373 views
  • 6
    Integrating Azure Cognitive Search into ASP.NET Core Appli… 156 views
  • 7
    Integrating Anthropic Claude API in ASP.NET Core for AI Ch… 141 views

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 26192 views
  • Exception Handling Asp.Net Core 20938 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20391 views
  • How to implement Paypal in Asp.Net Core 19753 views
  • Task Scheduler in Asp.Net core 17705 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