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>
I tried a lot of workarrounds and non of them worked for me. The exception was "The required anti-forgery form field "__RequestVerificationToken" .
What helped me out was to switch form .ajax to .post:
Another (less javascriptish) approach, that I did, goes something like this:
First, an Html helper
that will return a string
so we can use it like this
And it seems to work!
In Asp.Net Core you can request the token directly, as documented:
And use it in javascript:
You can add the recommended global filter, as documented:
In Account controller:
In View:
It is important to set
contentType
to'application/x-www-form-urlencoded; charset=utf-8'
or just omitcontentType
from the object ...