Search code examples
javascriptajaxasp.net-mvchttpantiforgerytoken

Use AntiForgeryToken in ajax - mvc5


How I can solve this problem:

The required anti-forgery form field "__RequestVerificationToken" is not present.

I have read a lot of forums but a can't find out a solution. It seems the AntiForgeryToken is not send but I've got not idea how i could do it.

In my view I've include @Html.AntiForgeryToken(), my controller has [ValidateAntiForgeryToken].

 var http = new XMLHttpRequest();
        var url = "..@actionInAPP"
        var token = $('input[name="__RequestVerificationToken"]').val();
        var params =serialize(document.forms[@numForm]);
        console.log(params);

        http.open("POST", url, true);

           var form_data = new FormData(document.forms[@numForm]);
           return $.ajax({
             type: 'POST',
             url: url,
             contentType: false,
             processData: false,
             headers: { '__RequestVerificationToken': token },
             complete: function(){
                http.onreadystatechange = function () {
                     if (http.readyState == 4 && http.status == 200) {
                        window.location.reload();
                     }
                     if (http.readyState == 4 && http.status == 400) {
                        document.getElementById("@targetId").innerHTML = http.responseText;
                     }
                 }
                http.send(params);
            },
          });

The information is saved in DB but in my browser I have this 500 error POST http://localhost:xxxx/xyz/Create 500 (Internal Server Error)

what is the problem here?


Solution

  • I got it!!! i changed the $ajax and it worked perfect

    return $.ajax({
                 type: 'POST',
                 url, url,
                 contentType: false,
                 processData: false,
                 data: form_data,
                 Success: function(){
                    http.send(params);
                 },
                complete: function(http){
                    if (http.readyState == 4 && http.status == 200) {
                        window.location.reload();
                    }
                    if (http.readyState == 4 && http.status == 400) {
                        document.getElementById("@targetId").innerHTML = http.responseText;
                    }
               }
            });