AJAX调用时出现“所需的防伪表单字段__requestverificationtoken不存在”错误。

3
所有以上的答案都没有帮助到我。当我使用Jquery Ajax调用时,我会在请求中得到这个错误信息:

"所需的防伪表单字段 "__RequestVerificationToken" 不存在"

如果我在POST操作方法中注释掉 [ValidateAntiForgeryToken] 属性,它就能正常工作。我想知道为什么会出现这个错误。 如何在MVC中使用防伪标记进行ajax请求 将AntiForgeryToken发送到MVC Action方法,而无需表单验证
@using (Html.BeginForm("Save", "AddPost", FormMethod.Post, new { id = "CreateForm" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>GropPost_Table</h4>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.Body, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.Body, new { id = "Bf" })
                @Html.ValidationMessageFor(model => model.Body)
            </div>
        </div>


        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input id="btnAdd" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}  

  [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Save([Bind(Include = "Body")] GropPost_Table groppost_table)
        {

            if (ModelState.IsValid)
            {

                groppost_table.GroupID = 1;
                groppost_table.ID = 1;
                groppost_table.PostDate = System.DateTime.Now;
                db.GropPost_Table.Add(groppost_table);
                db.SaveChanges();
                return Json(groppost_table);
            }

            else
            {

                return Json("we Couldent add your post");
            }
        }

<script type="text/javascript">

    $("#btnAdd").click(function () {

        var GropPost_Table = {
            "Body": $("#Bf").val()       
        };

        var token = $('#CreateForm input[name=__RequestVerificationToken]').val()

        var headers = {};

        headers['__RequestVerificationToken'] = token;


        $.ajax( {
            type: "POST",
            url: "@Url.Action("Save","AddPost")",
            data: JSON.stringify(GropPost_Table),
            contentType: "application/json;charset=utf-8",
            processData: true,
            headers:headers,
            success: function (dataR) {
                $("#Bf").val('');
           },
            error: function (dataR) {
                $("#Bf").val('');
                alert(dataR.toString());
            }
        });
    });
    </script>

1
你的 header 设置没有使用正确的语法 - 它应该是一个带有键/值对的对象。查看你链接中第二个问题的顶部答案以获取解决方案。 - Rory McCrossan
1
@RoryMcCrossan 我修改了代码!但是仍然出现那个错误! - Mohammad Olfatmiri
1个回答

0

我一直将请求验证令牌包含在POST数据中而不是头部。 我会这样处理:

首先,在您的输入按钮中添加type="submit",以便单击时提交表单。 然后在您的JavaScript中:

// Listen for the submit event on the form
$('#CreateForm').on('submit', function(event) { 
    var $form = $(this);

    $.ajax({
        // Html.BeginForm puts the url in the 
        // "action" attribute
        url: $form.attr('action'),
        // Serializing the form will pick up the verification
        // token as well as other input data
        data: $form.serialize(),
        success: function(dataR) {
            $('#Bf').val('');
        },
        error: function(dataR) {
            $('#Bf').val('');
            alert(dataR.toString());
        }
    });

    // Preventing the default action will keep the form
    // from doing a full POST.
    event.preventDefault();
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接