Akmal Salikhov
Akmal Salikhov

Reputation: 872

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

There really is a lot of info about this problem in internet, but nothing is helped me.

That is my client code:

var token = $('form[action="/Storage/AddReceipt"] input[name="__RequestVerificationToken"]').val();


var addAntiForgeryToken = function(data) {
    data.__RequestVerificationToken = token;
    return data;
};
var success = function (result) {
    alert(result.success);
};

$.ajax({
    url: '@Url.Action("AddReceipt", "Storage")',
    type: 'POST',
    contentType: 'application/json',
    data: addAntiForgeryToken({ Number: 1, BatchDate: '24/03/2015' }),
    success: success,
    error: function (xhr, textStatus, errorThrown) {
        alert(errorThrown);
    }
});

and controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddReceipt(...) {...}

and server response to my requerst -

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

but correct token is sending:

enter image description here

return JSON.stringify(data);

and

$.ajax({
            ...
            data: $('form[action="/Storage/AddReceipt"]').serialize(), 
            ...
            }

doesnt help too.

Upvotes: 1

Views: 1353

Answers (1)

Madhu
Madhu

Reputation: 2551

You missed to add the __RequestVerificationToken to the request headers. Add it as follows.

$.ajax({
url: '@Url.Action("AddReceipt", "Storage")',
type: 'POST',
contentType: 'application/json',
headers:{__RequestVerificationToken : token},
data: JSON.stringify(addAntiForgeryToken({ Number: 1, BatchDate: '24/03/2015' })),
success: success,
error: function (xhr, textStatus, errorThrown) {
    alert(errorThrown);
}
});

We must add the anti forgery token to the request header.

Upvotes: 1

Related Questions