gpt4 book ai didi

jquery - Ajax POST 中不存在 __RequestVerificationToken

转载 作者:行者123 更新时间:2023-12-01 03:32:37 25 4
gpt4 key购买 nike

我正在使用 jQuery DataTales 从 MVC5 请求 POST URL 并尝试添加防伪 token 。我已将其添加到 header 和请求正文中,但仍然收到 500 错误:“所需的防伪表单字段“__RequestVerificationToken”不存在。”

形式:

<form id="my-units-form" action="@Url.Action("MyUnitsResults", "Provider")" class="form-horizontal criteria well well-sm">
@Html.AntiForgeryToken()
....

JavaScript:

$userDt = $('#users-table')
.DataTable({
serverSide: true,
ordering: false,
searching: true,
ajax: {
"url": url,
"type": "POST",
'contentType': 'application/json',
"dataType": "json",
headers: { '__RequestVerificationToken': $('form input[name=__RequestVerificationToken]').val() },
data: function (d) {
d.__RequestVerificationToken= $('form input[name=__RequestVerificationToken]').val();

return JSON.stringify(d);
}
},

Headers

Payload

最佳答案

如果您对数据进行字符串化并使用 contentType: 'application/json,则仅将 token 添加到 ajax header (不会从正文中读取)。

然后,您需要创建一个自定义 FilterAttribute 来从标题中读取值

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class ValidateHeaderAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}

var httpContext = filterContext.HttpContext;
var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);
}
}

并在您的 Controller 方法中,将 [ValidateAntiForgeryToken] 属性替换为 [ValidateHeaderAntiForgeryToken]

关于jquery - Ajax POST 中不存在 __RequestVerificationToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46468376/

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