使用jQuery Ajax和Html.AntiForgeryToken()时,防伪表单字段"__RequestVerificationToken"不存在

Ron*_*nyK 6 jquery asp.net-mvc-4

我为这个问题的接受答案中描述的解决方案实现了Razor等价物: jQuery Ajax调用和Html.AntiForgeryToken() 但是我一直得到以下异常:

System.Web.Mvc.HttpAntiForgeryException(0x80004005):不存在所需的防伪表单字段"__RequestVerificationToken".

编辑

我这样做是为了解决这个问题:

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;

    //If there is a custom error handler nullify the general statusCode setting.
    if (error) {
        ajaxOptions.error = error;
        ajaxOptions.statusCode = null;
    };

    $.ajax(ajaxOptions);
}
Run Code Online (Sandbox Code Playgroud)

但不幸的是,FormData()仅在最新的浏览器版本中受支持.在FormData()之前可以使用的任何解决方法?

编辑 我想知道为什么ValidateAntiForgeryTokenAttribute只在Form数据中查找AntyForgeryToken,并且不会在溃败值中查找它,如下面密码类AntiForgeryTokenStoreAntiForgeryWorker的代码中所示

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);
}
Run Code Online (Sandbox Code Playgroud)

Ron*_*nyK 5

好吧,在挖掘了更多之后,我在此链接中找到了一个很好的解决我的问题的方法: ASP.NET MVC Ajax CSRF Protection With jQuery 1.5

据我了解在这个问题的选择答案中描述的解决方案:jQuery Ajax 调用和 Html.AntiForgeryToken(),不应该工作(实际上它对我来说失败了)。