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
Create antiforgerytoken:
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
<input ...>
}
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;
});
When you call CallAjax()
, where is data
coming from? I ask because, usually when your data comes from a form then your CSRF token is already part of the form, typically in a hidden field.
<form action="yourPage.html" method="POST">
<input type="hidden" name="__RequestVerificationToken" value="......"/>
.... other form fields ....
</form>
So if your data is all coming from a form, then you should just make sure that the token is a hidden part of that form and the token should automatically be included.
If your data is coming from somewhere other than a form, then it is understandable that you would stash your token somewhere and then include it after the data has been assembled. But you might consider adding the token to the data, rather than building a new object from the token and then adding all the data to it.
if (type == 'POST') {
data._RequestVerificationToken = $("input[name='__RequestVerificationToken']").val();
ajaxOptions.processData = false;
ajaxOptions.contentType = false;
}
Well, after digging some more I found a nice solution to my problem in this link: ASP.NET MVC Ajax CSRF Protection With jQuery 1.5
As far as I understand the solution described in the chosen answer for this question: jQuery Ajax calls and the Html.AntiForgeryToken(), shouldn't work (indeed it failed for me).