I am currently developing an MVC application in ASP.net. I am using AJAX.ActionLink to provide a delete link in a list of records, however this is very insecure. I have put
To piggyback on the $.ajaxPrefilter
answers, I added the token to both options
and originalOptions
rather than the jqXHR
headers. This does require the token to be somewhere in a form on your page.
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
var token = $('input[name="__RequestVerificationToken"]');
if (token.length > 0) {
var data = options.data;
var dataArray = originalOptions.data;
if (data && !data.includes('__RequestVerificationToken')) {
options.data = data + '&__RequestVerificationToken=' + token.val();
}
if (dataArray && !('__RequestVerificationToken' in dataArray)) {
var tokenObject = { name: '__RequestVerificationToken', value: token.val() };
originalOptions.data.push(tokenObject);
}
}
});
Keep in mind that this will add this token to every single AJAX request on your page, so you may want to filter by the options.url
string or options.type == 'POST'
.