Skip to content

Instantly share code, notes, and snippets.

@scottrippey
Created August 22, 2012 18:21
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save scottrippey/3428114 to your computer and use it in GitHub Desktop.
Save scottrippey/3428114 to your computer and use it in GitHub Desktop.
ASP.NET MVC AntiForgeryToken + AJAX = jQuery to the rescue
// Setup CSRF safety for AJAX:
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
if (options.type.toUpperCase() === "POST") {
// We need to add the verificationToken to all POSTs
var token = $("input[name^=__RequestVerificationToken]").first();
if (!token.length) return;
var tokenName = token.attr("name");
// If the data is JSON, then we need to put the token in the QueryString:
if (options.contentType.indexOf('application/json') === 0) {
// Add the token to the URL, because we can't add it to the JSON data:
options.url += ((options.url.indexOf("?") === -1) ? "?" : "&") + token.serialize();
} else if (typeof options.data === 'string' && options.data.indexOf(tokenName) === -1) {
// Append to the data string:
options.data += (options.data ? "&" : "") + token.serialize();
}
}
});
@weedkiller
Copy link

i have the same problem

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment