【发布时间】:2021-01-07 12:50:42
【问题描述】:
我正在尝试使用 ValidateAntiForgeryToken 来防止对我的应用程序进行跨站点伪造。一直报错
所需的防伪表单字段 __requestverificationtoken 不存在
看到很多关于此的讨论,但我无法提出解决方案。
代码:
在我的 Index.cshtml 中,设置 AntiForgeryToken:
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
@Html.AntiForgeryToken()
}
在我的 ajax.utilities post 方法中,设置令牌:
var post = function (options, callbacks) {
// set default POST options
options.type = "POST";
options.dataType = options.dataType !== undefined ? options.dataType : "json";
options.contentType = options.contentType !== undefined ? options.contentType : "application/json; charset=utf-8";
var form = $('#__AjaxAntiForgeryForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
return sendRequest(options, callbacks);
};
我的 jquery 正确设置了标题,即“X-Requested-With”:
if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
最后在我的控制器中,我指定了 HttpPost 和 ValidateAntiForgery 属性:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateComposite(string name, int compositeTypeId, int componentTypeId, DateTime inceptionDate)
{
return DispatchCommandWithJsonReturn(new CompositeCommands.CreateComposite(name, compositeTypeId, componentTypeId, inceptionDate));
}
我仍然收到错误所需的防伪表单字段 __requestverificationtoken 不存在
使用 MVC 5,我不知道这是否相关
有什么想法吗?
edit:我在网站上的其他地方看到过这个问题,试图提出修改建议,但无济于事。
【问题讨论】:
标签: javascript vue.js validation model-view-controller