include antiforgerytoken in ajax post ASP.NET MVC

I am having trouble with the AntiForgeryToken with ajax. I’m using ASP.NET MVC 3. I tried the solution in jQuery Ajax calls and the Html.AntiForgeryToken(). Using that solution, the token is now being passed:

var data = { ... } // with token, key is '__RequestVerificationToken'

$.ajax({
        type: "POST",
        data: data,
        datatype: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        url: myURL,
        success: function (response) {
            ...
        },
        error: function (response) {
            ...
        }
    });

When I remove the [ValidateAntiForgeryToken] attribute just to see if the data (with the token) is being passed as parameters to the controller, I can see that they are being passed. But for some reason, the A required anti-forgery token was not supplied or was invalid. message still pops up when I put the attribute back.

Any ideas?

EDIT

The antiforgerytoken is being generated inside a form, but I’m not using a submit action to submit it. Instead, I’m just getting the token’s value using jquery and then trying to ajax post that.

Here is the form that contains the token, and is located at the top master page:

<form id="__AjaxAntiForgeryForm" action="#" method="post">
    @Html.AntiForgeryToken()
</form>

13 Answers
13

Leave a Comment