Wednesday, 15 February 2017

How to Send and Verify OTP On Mobile No Using C# In Asp.Net

2/15/2017 - By Pranav Singh 18

This article will show you how you can generate the OTP in asp.net using C# and send it via SMS for verification using c#.net.

So in this article first we will create a new asp.net application and add a page for generating the OTP.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SendOTP.aspx.cs" Inherits="Shoping_Cart.SendOTP" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to Send and Verify OTP On Mobile No Using C# In Asp.Net</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            Mobile No:
        <asp:TextBox ID="txtMobileNo" runat="server" Width="241px"></asp:TextBox>
             <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Send OTP" />

            <br />
            <asp:Label ID="lblMessage" runat="server" style="color: #FF0000" Text=""></asp:Label>

        </div>
    </form>
</body>
</html>

Now on button click we will add the below code.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Shoping_Cart
{
    public partial class SendOTP : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                //For generating OTP
                Random r = new Random();
                string OTP = r.Next(1000, 9999).ToString();

                //Send message
                string Username = "youremail@domain.com";
                string APIKey = "YourHash";//This may vary api to api. like ite may be password, secrate key, hash etc
                string SenderName = "MyName";
                string Number = "9876543210";
                string Message = "Your OTP code is - " + OTP;
                string URL = "http://api.urlname.in/send/?username=" + Username + "&hash=" + APIKey + "&sender=" + SenderName + "&numbers=" + Number + "&message=" + Message;
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                StreamReader sr = new StreamReader(resp.GetResponseStream());
                string results = sr.ReadToEnd();
                sr.Close();

                //Store the OTP in session to verify in next page.
                //If you want to verify from DB store the OTP in DB for verification. But it will take space
                Session["OTP"] = OTP;

                //Redirect for varification
                Response.Redirect("VerifyOTP.aspx");
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message.ToString();
            }
        }

    }
}

In above code I have generated the OTP of four digit,. After generating the send the OPT to sms using SMS api with the help of HttpWebRequest. For this you need SMP appi account detail. 
After generating OPT I have stored the OPT in session and then redirected to the next page. By doing this we don’t need to store the OTP in DB. Just redirect the verification page.

Here is the code of verification page.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="VerifyOTP.aspx.cs" Inherits="Shoping_Cart.VerifyOTP" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Verify OTP</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            OTP:
        <asp:TextBox ID="txtOTP" runat="server" Width="241px"></asp:TextBox>
             
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Verify OTP" />
            <br />
            <asp:Label ID="lblMessage" runat="server" style="color: #FF0000" Text=""></asp:Label>
        </div>
    </form>
</body>
</html>

Code for OPT verification page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Shoping_Cart
{
    public partial class VerifyOTP : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Session["OTP"].ToString() == txtOTP.Text)
            {
                lblMessage.Text = "You have enter correct OTP.";
                Session["OTP"] = null;
            }
            else
            {
                lblMessage.Text = "Pleae enter correct OTP.";
            }
        }
    }
}

Here I have checked the session value with the entered value. If it’s match you can proceed to next level. Otherwise throw error message.


Now lets execute and check the processing.

 Now enter the mobile no and click on send OTP. Now system will generate the OTP and send via SMS.



Now on verification page add a wrong OTP. You will get error message.



Now enter correct OPT you will get success message.


About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

18 comments:

  1. The underlying connection was closed: The connection was closed unexpectedly.
    this error display at runtime. gives solution

    ReplyDelete
  2. Resend otp code and otp time show display and warnings page not close and refreshing

    ReplyDelete
    Replies
    1. Not able to understand you issue. Please explain it.

      Delete
  3. the string url that need to put what url?

    ReplyDelete
    Replies
    1. Here URL is the SMS API url which u get from your service provider.

      Delete
  4. Object reference not set to an instance of an object

    ReplyDelete
    Replies
    1. Hi Badal,

      In which line of code you are getting error.

      Delete
  5. I have used the code. There are no error but the I'm not get the varification. Why?

    ReplyDelete
  6. i want to reset password by gmail auto generate otp

    ReplyDelete
    Replies
    1. For that u need to enable pop in gmail and then user code to send email having random password string,

      Delete
  7. i want to reset password by gmail auto generate otp in asp.net mvc

    ReplyDelete
  8. Help me this, please " The remote name could not be resolved: 'api.urlname.in'"
    when i fill in a phone no and click sendOTP

    ReplyDelete
  9. Parser Error
    Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

    Parser Error Message: Could not load type 'Shoping_Cart.VerifyOTP'.

    Source Error:


    Line 1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="VerifyOTP.aspx.cs" Inherits="Shoping_Cart.VerifyOTP" %>
    Line 2:
    Line 3:

    Source File: /VerifyOTP.aspx Line: 1

    Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1590.0

    ReplyDelete
  10. Server Error in '/' Application.
    Parser Error
    Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

    Parser Error Message: Could not load type 'SendOTP'.

    Source Error:


    Line 1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SendOTP.aspx.cs" Inherits="SendOTP" %>
    Line 2:
    Line 3:

    Source File: /SendOTP.aspx Line: 1

    Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1590.0

    ReplyDelete
  11. getting error while i have attempt this
    The remote server returned an error: (405) Method Not Allowed.

    ReplyDelete

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top