Wednesday, 6 November 2024

Send OTP Using C# MVC5

 



This blog post will guide you through implementing OTP verification during user signup using C# in ASP.NET MVC5. I've simplified the steps to make the OTP verification process clear and easy to Implement.

HTML

<form method="post">
    <input type="hidden" name="OTP1" value="@ViewBag.otp" />
    <input type="number" name="OTP2" required autofocus  class="gtxt " placeholder="OTP" /><br />
    <p style="text-align:center">
       <input type="submit" value="Submit" class="btn btn-info gbtn" />
        <a href="/Home">
            <input type="button" value="Cancel" class="btn btn-danger gbtn" />                          </a><br />
         <span style="color:red">@ViewBag.Err </span>
         </p>
</form>

Action

public ActionResult otp()
{
     SelectRepository ob = new SelectRepository();
     Random obr = new Random();
     int ran = obr.Next();
     string otp = ran.ToString().Substring(0, 5);
     string phone = "", url = "";
     phone = "9999999999";
     url = "https://2factor.in/API/V1/enter-your-key/SMS/" + phone + "/" + otp + "/OTP1";           WebRequest request = HttpWebRequest.Create(url);
     WebResponse response = request.GetResponse();
     StreamReader reader = new StreamReader(response.GetResponseStream());
     string urlText = reader.ReadToEnd(); // it takes the response from your url. now you can use as your need 
     ViewBag.result = urlText; // for your reference output from SMS provider                       ViewBag.otp = otp; // otp saved for verification
      return View();
}


Verifiy OTP

[HttpPost]
public ActionResult otp(LoginModel data)
{
   if (Convert.ToInt32(data.OTP1) == Convert.ToInt32(data.OTP2))
   {       
       return RedirectToAction("successurl", "actionname");
    }
    else
         return RedirectToAction("err", "common", new { msg = "Invalid OTP", color = "red" });
}



No comments:

Post a Comment