ASP.NET MVC中使用AJAX防止恶意请求的解决方法可以通过以下步骤来实现:
@using (Html.BeginForm("ActionName", "ControllerName"))
{
@Html.AntiForgeryToken()
// 表单内容
}
$.ajax({
url: '/ControllerName/ActionName',
type: 'POST',
data: {
__RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
// 其他请求参数
},
success: function (response) {
// 请求成功的处理
},
error: function (xhr, status, error) {
// 请求失败的处理
}
});
[ValidateAntiForgeryToken]
属性来验证请求的合法性。如果请求中的AntiForgeryToken无效,服务器将返回错误信息。[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ActionName(FormViewModel model)
{
if (ModelState.IsValid)
{
// 处理请求
return RedirectToAction("SuccessAction");
}
else
{
return View(model);
}
}
通过以上的解决方法,可以有效地防止恶意请求的发生,并保护应用程序的安全性。