I checked:
How can i supply an AntiForgeryToken when posting JSON data using $.ajax?
how can i use AntiForgeryToken with JSON post in mvc 4
and tried everything mentioned. Sadly, nothing proposed worked.
var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers['__RequestVerificationToken'] = token;
var data = serializeData(token);
$.ajax(
{
cache: false,
async: false,
type: 'POST'
url: url
data: data,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
headers: headers,
success: function (result) {
},
error: function () {
e.stopPropagation();
}
});
function serializeData(token) {
var data = {
__RequestVerificationToken: token,
MyJsonData : JSON.stringify(myFormData),
};
return data;
}
I always get the exception that the RequestVerificationToken
is not present.
However, if I exclude contentType
parameter from the ajax call, it successfully verifies the token, but the MyJsonData is null in the controller, and it comes with the exception:
{"The parameter conversion from type 'System.String' to type 'MyJsonData' failed because no type converter can convert between these types."}
I also try to send the token as part of the header of the request, but that also does not work.