Here I will explain how to generate random one time password or otp in asp.net using c#.
In this we will generate otp using capital and small letters and numbers.
Default.aspx :
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Generate Random OTP in Asp.net(C#),Asp.net using C#</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="BtnGenerateOTP" Text="Generate" runat="server" OnClick="BtnGenerateOTP_Click" /><br />
<asp:Label ID="lblDisplayOTP" runat="server" />
</div>
</form>
</body>
</html>
Default.aspx.cs
protected void BtnGenerateOTP_Click(object sender, EventArgs e)
{
// declare array string to generate random string with combination of small,capital letters and numbers
char[] charArray = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
string strrandom = string.Empty;
Random objrandom = new Random();
int noofcharacters = 7;//change OTP length as per your requirment like 1,2,3,4,5,6
for (int i = 0; i < noofcharacters; i++)
{
//It will not allow Repetation of Characters
int pos = objrandom.Next(1, charArray.Length);
if (!strrandom.Contains(charArray.GetValue(pos).ToString()))
strrandom += charArray.GetValue(pos);
else
i--;
}
lblDisplayOTP.Text = strrandom;
}
Default.aspx :
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Generate Random OTP in Asp.net(C#),Asp.net using C#</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="BtnGenerateOTP" Text="Generate" runat="server" OnClick="BtnGenerateOTP_Click" /><br />
<asp:Label ID="lblDisplayOTP" runat="server" />
</div>
</form>
</body>
</html>
Default.aspx.cs
protected void BtnGenerateOTP_Click(object sender, EventArgs e)
{
// declare array string to generate random string with combination of small,capital letters and numbers
char[] charArray = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
string strrandom = string.Empty;
Random objrandom = new Random();
int noofcharacters = 7;//change OTP length as per your requirment like 1,2,3,4,5,6
for (int i = 0; i < noofcharacters; i++)
{
//It will not allow Repetation of Characters
int pos = objrandom.Next(1, charArray.Length);
if (!strrandom.Contains(charArray.GetValue(pos).ToString()))
strrandom += charArray.GetValue(pos);
else
i--;
}
lblDisplayOTP.Text = strrandom;
}
Comments
Post a Comment