I applied the Razor equivalent to the solution described in the accepted answer to this question: jQuery Ajax calls and Html.AntiForgeryToken () But I kept getting the following exception:
System.Web.Mvc.HttpAntiForgeryException (0x80004005): An anti-fake field of the form "__RequestVerificationToken" is not required.
change
I managed to get around this:
function AddAntiForgeryToken(data) { data.append('__RequestVerificationToken',$('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val()); return data; }; function CallAjax(url, type, data, success, error) { var ajaxOptions = { url: url, type: type, contentType: 'application/json'}; if (type == 'POST') { var fd = new window.FormData(); fd = AddAntiForgeryToken(fd); $.each(data, function (i, n) { fd.append(i,n); }); data = fd; ajaxOptions.processData = false; ajaxOptions.contentType = false; } ajaxOptions.data = data; if (success) ajaxOptions.success = success;
But, unfortunately, FormData () formats are supported only in the latest browser versions. Any workaround that may work before FormData (), as introduced?
change I wonder why the ValidateAntiForgeryTokenAttribute searches for the AntyForgeryToken only in the form data and does not look for it in the route values, as you can see below in the code of the closed classes AntiForgeryTokenStore and AntiForgeryWorker?
public void Validate(HttpContextBase httpContext) { this.CheckSSLConfig(httpContext); AntiForgeryToken cookieToken = this._tokenStore.GetCookieToken(httpContext); AntiForgeryToken formToken = this._tokenStore.GetFormToken(httpContext); this._validator.ValidateTokens(httpContext, AntiForgeryWorker.ExtractIdentity(httpContext), cookieToken, formToken); } public AntiForgeryToken GetFormToken(HttpContextBase httpContext) { string serializedToken = httpContext.Request.Form[this._config.FormFieldName]; if (string.IsNullOrEmpty(serializedToken)) return (AntiForgeryToken) null; else return this._serializer.Deserialize(serializedToken); }
Ronyk source share