gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:50:58 26 4
gpt4 key购买 nike

我实现了与此问题的已接受答案中描述的解决方案等效的 Razor: jQuery Ajax calls and the Html.AntiForgeryToken() 但我不断收到以下异常:

System.Web.Mvc.HttpAntiForgeryException (0x80004005): The required anti-forgery form field "__RequestVerificationToken" is not present.

编辑

我设法解决这个问题:

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,而不在路由值中查找它,正如您在下面的密封类代码 AntiForgeryTokenStore< 中看到的那样/em> 和 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);
}

最佳答案

好吧,在深入研究之后,我在此链接中找到了解决问题的好方法: ASP.NET MVC Ajax CSRF Protection With jQuery 1.5

据我了解此问题所选答案中描述的解决方案:jQuery Ajax calls and the Html.AntiForgeryToken() ,不应该工作(事实上它对我来说失败了)。

关于jquery - 使用 jQuery Ajax 和 Html.AntiForgeryToken() 时,防伪表单字段 "__RequestVerificationToken"不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16793516/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com