我正在构建一个ASP.NET Core应用程序,在该应用程序中,我将OTP发送给用户,用户必须在30秒内输入OTP才能工作。如何检查用户在输入字段中输入的OTP是否在生成OTP后30秒内输入?
我已经编写了控制器,用于生成、获取和提交OTP。只需要了解OTP生成的时间检查逻辑。
控制器
[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;
return RedirectToAction("GenerateOtp", "Home");
}
[HttpPost]
public IActionResult SubmitOtp([FromForm] int finalDigit, int sentotp)
{
if (finalDigit == null)
return NoContent();
else if (finalDigit == sentotp && ***30 Second Check Here***)
{
return Ok("Activated Successfully");
}
else if(!(***30 Second Check Here***))
{
return BadRequest("OTP Timedout");
}
else
{
return BadRequest("Please Enter Valid 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>
<br />
<input type="number"/>
<br />
<input type="submit" value="SubmitOtp" class="btn btn-primary btn-lg"/>
</form>发布于 2022-04-12 08:19:47
与保存到临时数据中的OTP一样,您可以在SendOtp操作方法中发送OTP时保存时间戳。在SubmitOtp操作方法中,从TempData读取时间戳。如果当前时间戳与TempData时间戳之间的差值超过30秒,则拒绝请求。
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");
}
[HttpPost]
public IActionResult SubmitOtp([FromForm] int finalDigit, int sentotp)
{
if (finalDigit == null)
return NoContent();
else if (finalDigit == sentotp && **30 Second Check Here**)
{
return Ok("Activated Successfully");
}
else if((DateTime.Now - Convert.DateTime(TempData["timestamp"])).TotalSeconds > 30)
{
return BadRequest("OTP Timedout");
}
else
{
return BadRequest("Please Enter Valid OTP");
}
}https://stackoverflow.com/questions/71838454
复制相似问题