在 asp.net MVC 中将 ValidateAntiForgeryToken 与 JQGrid 一起使用?

Use ValidateAntiForgeryToken with JQGrid in asp.net MVC?

在混合 asp.net web forms/mvc 5.2.6 应用程序中,使用 JQuery.jqGrid v4.4.4,我正在努力寻找一种在控制器上使用 ValidateAntiForgeryToken 属性的方法jqGrid post 在获取其数据时使用的方法。

网格是read-only。 "datatype" 是 "json" 而 "mtype" 是 "POST"。我试过简单地将 __RequestVerificationToken 隐藏输入的值附加到数据中,然后 post 返回到控制器,但这不起作用;该站点只是抛出一个丢失的防伪令牌异常。

我注意到,当有人想将 json 数据的 $.ajax post 传递给控制器​​方法时,可以将 __RequestVerificationToken 传递给 "headers" 参数。虽然 jqGrid 在幕后进行 $.ajax 调用,但不幸的是它没有 headers 参数。

我在 SO 上找到了示例,其中可以通过 editData 参数传递令牌(例如:),但我的网格是 read-only,无论如何我想要在用户输入搜索条件然后单击按钮填充网格时强制执行令牌。

有什么方法可以在填充 jqgrid 时使用 ValidateAntiForgeryToken 吗?

您可以将 postData 参数与 __RequestVerificationToken 属性 定义为以下函数:

postData: {
    __RequestVerificationToken: function () {
        return jQuery("input[name=__RequestVerificationToken]").val();
    }
}

它会在填充网格期间向服务器发送的所有请求添加__RequestVerificationToken参数。

Oleg 的回答对我来说是正确的答案,但我也从 https://github.com/VahidN/jqGrid-Samples/blob/master/jqGrid04/jqGrid04/Views/Home/Index.cshtml 中偶然发现了这个更广泛的解决方案,它将验证令牌添加到每个 ajax POST:

$(document).ajaxSend(function (elm, xhr, s) {
        let securityToken = $('[name=__RequestVerificationToken]').val();
        if (s.type === 'POST' && typeof securityToken != 'undefined') {
            if (s.data.length > 0) {
                s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
            else {
                s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
        }
    });