anti-forgery form field “__RequestVerificationToken” is not present when using jQuery Ajax and the Html.AntiForgeryToken()

后端 未结 3 1462
一生所求
一生所求 2020-12-20 20:20

I implemented the Razor equivalent for the solution described in the accepted answer for this Question: jQuery Ajax calls and the Html.AntiForgeryToken() But I kep

3条回答
  •  独厮守ぢ
    2020-12-20 20:47

    Create antiforgerytoken:

    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        
    }
    

    Create a function to add the token to the ajax request :

    function addRequestVerificationToken(data) {
        data.__RequestVerificationToken=$('input[name=__RequestVerificationToken]').val();
        return data;
    };
    

    You can then use it like this:

    $.ajax({
       type: "POST",
       url: '@Url.Action("MyMethod", "MyController", new {area = "MyArea"})',
       dataType: "json",
       traditional: true,
       data: addRequestVerificationToken( { "id": "12345678" } );
    })
    .done(function(result) {
       if (result) {
           // Do something
       } else {
           // Log or show an error message
       }
       return false;
    });
    

提交回复
热议问题