我在Jquery Ajax调用的请求中收到此错误。
“所需的防伪表格字段”__RequestVerificationToken“不存在”
所以我找到了一些解决方案并且我应用了workround,但是看起来它并不适合我。
我的请求电话:
$("#btn-save-survey").click(function (e) {
e.preventDefault();
var validationForm = $('#surveyForm').valid();
if (!validationForm) {
//$btn.button('reset');
//$("#loadingSaveSampling").addClass('hidden');
return;
}
var token = $('#surveyForm input[name="__RequestVerificationToken"]').val();
var dataRequest = JSON.stringify(
{
"__RequestVerificationToken": token,
"v1": $("v1").val(),
"v2": $("v2").val(),
"v3": $("v3").val(),
"v4":$("v4").val(),
"v5": $("v5").val(),
"v6": $("v6").val()
});
$.ajax({
type: "POST",
url: $("#url-xx").val() + "/test/xxxx",
data: dataRequest,
dataType: "json",
contentType: "application/json",
success: function (response) {
alert("sucesso=> " + response);
},
error: function (response) {
alert("erro=> " + response);
}
});
我的ActionResult:
HttpPost]
[Route("criar-pesquisa")]
[ValidateAntiForgeryToken]
[ValidateAjax]
public ActionResult Create([Bind(Exclude = "SurveyId")]SurveyForm form)
{
try
{
if (ModelState.IsValid)
{
AddOrUpdateSurvey(form);
return Json(new { Success = true });
//return RedirectToRoute(Routes.SamplingSurvey);
}
else
{
var modelStateErrors = ModelState.Values.SelectMany(x => x.Errors).Select(y => y.ErrorMessage);
return Json(new { status = false, errorMessage = modelStateErrors, stackError = "" }, JsonRequestBehavior.AllowGet);
}
}
catch (DataException dex)
{
ModelState.AddModelError(dex.Message, "Houve um erro para salvar a pesquisa. Tente novamente mais tarde.");
return Json(new { status = false, errorMessage = dex.Message, stackError = dex.StackTrace }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { status = false, errorMessage = ex.Message, stackError = ex.StackTrace }, JsonRequestBehavior.AllowGet);
}
}
我的表单我使用的是forgeryToke:
@using (Html.BeginCreateSurveyForm(new { role = "form", id = "myForm" }))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(m => m.id)
答案 0 :(得分:0)
var token = $('input[name=""__RequestVerificationToken""]').val();
var headers = {};
// other headers omitted
headers['__RequestVerificationToken'] = token;
$.ajax({
cache: false,
dataType: 'json',
type: 'POST',
headers: headers,
data: window.JSON.stringify(obj),
contentType: 'application/json; charset=utf-8',
url: '/some-url'
});