到目前为止,我一直在尝试将CSRF令牌添加到我的代码中,到目前为止还算不上运气。我认为有三个步骤:
我要发送的表单的代码:
@using (Html.BeginForm("Manage", "Account"))
{
@Html.AntiForgeryToken()
}
在控制器视图中,我写了:
public class HomeController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index()
{
return View("Table");
}
etc...
}
和我的ajax调用:
$.ajax({
type: "POST",
url: "../Home/" + sFunction,
contentType: "application/json; charset=utf-8",
processData: false,
dataType: "json",
headers: { "__RequestVerificationToken":
$('input[name=__RequestVerificationToken]').val() },
data: data === null ? null : JSON.stringify(data),
等
我想念什么?为什么它不起作用? 谢谢
答案 0 :(得分:2)
[ValidateAntiForgeryToken]
需要装饰您的表单发布方法。不是您的索引GET方法。在这种情况下...
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Manage(YourViewModel model)
{
//do your logic
return View(//whatever route & model)
}
,然后在js中将其添加到数据对象中。
let form = //get your form control here
let data = $(form).serialize();//form is your form control
data.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val();
$.ajax({
type: "POST",
url: //controller/action,
contentType: "application/x-www-form-urlencoded",
processData: false,
dataType: "json",
data: JSON.stringify(data),
//etc....
});