I've been looking at examples of how to do this on SO and as far as I can tell I've tried all the examples I can find with no success so far. I've tried altering some of the implementations to my scenario but this has thus far failed as well.
I have this on my page in _layout.cshtml so I always have a token available:
<form id="__AjaxAntiForgeryForm" action="#" method="post"> @Html.AntiForgeryToken()</form>
I also have this method in my JavaScript utils file:
AddAntiForgeryToken = function (data) {
data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
return data;
};
This is all working as expected and I get an anti forgery token. My actual posting code is:
myPage.saveData = function() {
var saveUrl = '/exercises/PostData';
var myData = JSON.stringify(myPage.contextsArrays);
$.ajax({
type: 'POST',
async: false,
url: saveUrl,
data: AddAntiForgeryToken({ myResults: myData }),
success: function () {
alert('saved');
},
dataType: 'json',
contentType: "application/json; charset=utf-8"
});
};
My action method looks like this:
[HttpPost, ValidateAntiForgeryToken, JsonExceptionFilter]
public JsonResult PostData(List<ResultsDc> myResults)
{
return Json(_apiClient.SubmitResults(myResults));
}
I've been testing this with the various implementations I've been trying and the response is always:
{"errorMessage":"The required anti-forgery form field \"__RequestVerificationToken\" is not present."}
I'm not posting a form it's just an array of data but checking the data that actually gets posted the Json doesn't look right (it's all encoded) but the __RequestVerificationToken parameter name is there and the token value is also present.
I'm pretty confused by all this at the moment and cannot find the correct way to send the token so that my MVC action is invoked. If I remove the ValidateAntiForgeryToken
attribute and have JSON.stringify(myPage.contextsArrays);
as the data the json looks correct (unencoded) and it maps fine.
How do I get this token posted properly without a form?