我为这个问题的接受答案中描述的解决方案实现了 Razor 等效项: jQuery Ajax calls and the 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);
}
但不幸的是,FormData() 仅在最新的浏览器版本中受支持。任何可以在 FormData() 引入之前起作用的解决方法?
编辑 我想知道为什么ValidateAntiForgeryTokenAttribute只在表单数据中查找 AntyForgeryToken,而不是在 rout 值中查找它,正如您在下面密封类AntiForgeryTokenStore和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);
}