Hi @wiss user,
Based on your description, I tested a simple example about session, you can refer to it.
public ActionResult Login()
{
return View();
}
private static int cntAttemps = 0;
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(UserProfile objUser)
{
if (ModelState.IsValid)
{
using (TestContext db = new TestContext())
{
var obj = db.UserProfile.Where(a => a.UserName.Equals(objUser.UserName) && a.Password.Equals(objUser.Password)).FirstOrDefault();
if (obj != null)
{
if (Session["Message"] == null)
{
cntAttemps = 1;
Session["UserID"] = obj.UserId.ToString();
Session["UserName"] = obj.UserName.ToString();
return RedirectToAction("UserDashBoard");
}
}
else
{
InvalidLoginAttemps();
}
}
}
return View(objUser);
}
private void InvalidLoginAttemps()
{
try
{
cntAttemps++;
Session["count"] = cntAttemps.ToString();
ModelState.AddModelError("", "Invalid login attempt.");
if (Convert.ToInt32(Session["count"]) > 3)
{
Session["Message"] = "Account Blocked. Try after some time.";
//code to block user
}
}
catch (Exception ex)
{
}
}
public ActionResult UserDashBoard()
{
return View();
}
@model WebMvc.Models.UserProfile
@{
ViewBag.Title = "Login";
}
@using (Html.BeginForm("Login", "Home", FormMethod.Post))
{
<fieldset>
<legend>Mvc Simple Login Application Demo</legend>
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@if (Session["Message"] != null)
{
<p style="border: 1px solid
red">
@Session["Message"]
</p>
}
<table>
<tr>
<td>@Html.LabelFor(a => a.UserName)</td>
<td>@Html.TextBoxFor(a => a.UserName)</td>
<td>@Html.ValidationMessageFor(a => a.UserName)</td>
</tr>
<tr>
<td>@Html.LabelFor(a => a.Password)</td>
<td>@Html.PasswordFor(a => a.Password)</td>
<td>@Html.ValidationMessageFor(a => a.Password)</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login" /></td>
<td></td>
</tr>
</table>
</fieldset>
}
<system.web>
<compilation debug="true" targetFramework="4.8" />
<httpRuntime targetFramework="4.8" />
<sessionState timeout="2"></sessionState>
</system.web>
Best regards,
Lan Huang
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.