簡體   English   中英

錯誤:必填的防偽表單字段“ __RequestVerificationToken”不存在

[英]error: The required anti-forgery form field "__RequestVerificationToken" is not present

我在請求Jquery Ajax調用時收到此錯誤。

“所需的反偽造表單字段“ __RequestVerificationToken”不存在”

因此,我找到了一些解決方案,並應用了解決方案,但發現它對我而言效果不佳。

我的請求電話:

$("#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);
        }
    });

我的動作結果:

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)
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'
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM