如何限制用户一次又一次地提交联系表单,而无需从 asp.net MVC 中的 IP 地址进行会话



我想限制用户一次又一次地从其IP地址提交联系表格。如何在 asp.net MVC中做到这一点?有人可以帮助我吗?我知道如何检索用户的IP,但我不知道如何使用它来限制用户再次提交表单

我的控制器代码

string IP = String.Empty;
System.Web.HttpContext current = System.Web.HttpContext.Current;
string IPAddress = current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if(!string.IsNullOrEmpty(IPAddress))
{
string[] valAddress = IPAddress.Split('.');
if(valAddress.Length != 0)
{
IP = valAddress[0];
}
}
IP = current.Request.ServerVariables["REMOTE_ADDR"];

有几种方法可以做到这一点。重要的问题是,你的工作规范是什么?

如果你开发公共网站,如stackoverflow或facebook等,你应该考虑在客户端和后端实现验证。如果您开发基于 Intranet 的 Web 应用程序,客户端验证就足够了。

如果您的表单是简单的联系表单类型,则应使用Google ReCaptcha来防止自动代码,机器人,以防止轰炸您的数据库或电子邮件。

https://www.google.com/recaptcha/intro/v3beta.html

以下是我如何实现防止用户发送多个。

[HttpPost]
public ActionResult Index(YourViewModel model)
{
#region backend validation
if (
!GoogleReCAPTCHAHelper.Check(Request["g-recaptcha-response"],
ConfigurationManager.AppSettings["GoogleReCAPTCHASecret"]))
{
ModelState.AddModelError(string.Empty, "You have to confirm that you are not robot!");
return View(model);
}
if ((from file in model.Files where file != null select file.FileName.Split('.')).Any(arr => arr[arr.Length - 1].ToLower() != "pdf"))
{
ModelState.AddModelError(string.Empty, "We only accept PDF files!");
return View(model);
}
if (model.Files.Count() > 2)
{
ModelState.AddModelError(string.Empty,
"You have exceeded maximum file upload size. You can upload maximum 2 PDF file!");
return View(model);
}
//// this stops the applicant sending the application multiple times within 5 minutes of a submition
DateTime? lastSubmission = null;
if (Request.Cookies["LastSubmission"] != null)
lastSubmission = Convert.ToDateTime(Request.Cookies["LastSubmission"].Value);
if (lastSubmission.HasValue && DateTime.Now < lastSubmission.Value.AddMinutes(5))
{
ModelState.AddModelError(string.Empty,
"ERROR: Your application has not been sent. This is due to receiving an application from you within the last five minutes. If you have made an error and wish to resend your application, please wait five minutes and then complete the application again.");
return View(model);
}
if (!ModelState.IsValid)
{
ModelState.AddModelError(string.Empty, "Something went wrong!");
return View(model);
}
#endregion
}

附言:模型。文件IEnumerable<HttpPostedFileBase>

最后但并非最不重要的一点是,当用户单击提交按钮时,您应该指示某种加载屏幕或禁用按钮以再次提交。因此,用户可以了解网站上发生的事情...

这是用于验证的 javascript 示例。

function sendForm() {
if (grecaptcha.getResponse() === "") {
event.preventDefault();
$("#robotErrorDiv").slideDown();
return false;
} else {
$("#robotErrorDiv").slideUp();
}
$("#myForm").validate();
if ($("#myForm").valid()) {
$("#loaderGif").fadeIn();
$("#submitButton").text("Sending...").attr("disabled", "disabled");
$("#myForm").submit();
}
return true;
}

只需在HTML5本地存储中添加一个变量,并在每次用户单击按钮时对其进行验证。

HTML 5本地无限期地存储数据,即使浏览器关闭并重新打开。 但是,如果用户清除本地存储,则他可以再次提交。但至少它会减少来自同一用户的点击次数。

有关 HTMl5 本地存储的更多信息,请参阅 https://www.w3schools.com/html/html5_webstorage.asp

最新更新