'Check if the entered OTP Code is right and within 30 seconds in ASP.NET Core MVC
I'm building an ASP.NET Core MVC Application in which when the user clicks on "Generate OTP" then a 4 digit OTP is shown to him on the screen and then he has to enter that OTP in an input field and click "Submit OTP" tp submit it. If the OTP is correct and is entered within 30 seconds then the user will be shown a success message otherwise the user will get an exception either that the OTP is timed-out or is incorrect.
I have written the controller code for generating the OTP, Sending it, and Submitting it.
The issue I'm facing is in the "VIEWS". I have made a button that on click shows the OTP to the user. How can I code in the view in such a way that the entered OTP in the input field is checked correctly?
**CONTROLLER**
using Microsoft.AspNetCore.Mvc;
using OTP_Sms_Verification.Models;
using System.Diagnostics;
namespace OTP_Sms_Verification.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult GenerateOtp()
{
return View();
}
[HttpPost]
public IActionResult SendOtp()
{
string num = "01223456789";
int len = num.Length;
string otp = string.Empty;
int otpDigit = 4;
string finalDigit;
int getIndex;
for (int i = 0; i < otpDigit; i++)
{
do
{
getIndex = new Random().Next(0, len);
finalDigit = num.ToCharArray()[getIndex].ToString();
} while (otp.IndexOf(finalDigit) != -1);
otp += finalDigit;
}
TempData["otp"] = otp;
TempData["timestamp"] = DateTime.Now;
return RedirectToAction("GenerateOtp", "Home");
}
[HttpGet]
public IActionResult SubmitOtp( int finalDigit)
{
if (finalDigit == null)
return NoContent();
else if ((DateTime.Now - Convert.ToDateTime(TempData["timestamp"])).TotalSeconds > 30)
{
return BadRequest("OTP Timedout");
}
else
{
return BadRequest("Please Enter Valid OTP");
}
}
}
}
**Generate OTP VIEW**
@{
ViewData["Title"] = "GenerateOtp";
}
<h1>GenerateOtp</h1>
<form method="post" asp-action="SendOtp" asp-controller="Home">
<br />
<input type="submit" value="GetOtp" class="btn btn-primary btn-lg"/>
<br />
<div>
@TempData["otp"]
</div>
<input type="number"/>
<br />
<input type="submit" value="SubmitOtp" class="btn btn-primary btn-lg"/>
</form>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
