【问题标题】:__requestverificationtoken error in javascript vue, MVC 5javascript vue,MVC 5中的__requestverificationtoken错误
【发布时间】: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


【解决方案1】:

我知道这是旧的,但如果有人遇到像我这样的问题,在我的情况下,问题出在表单的标签中,我必须添加 enctype = "multipart/form-data",所以当我将 __RequestVerificationToken 值添加到我的ajax 调用数据就可以了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-07
    • 2015-02-07
    • 2017-06-23
    • 1970-01-01
    • 2015-10-02
    • 1970-01-01
    • 2018-06-26
    • 2018-05-06
    相关资源
    最近更新 更多