使用 AXIOS 和 ValidateAntiForgeryToken 调用 MVC5 操作

Calling MVC5 action using AXIOS and ValidateAntiForgeryToken

我正在尝试使用 Axios 从我的 UI 调用标有 [ValidateAntiForgeryToken] 的控制器方法。

我已经使用 Jquery ajax

成功调用了相同的操作

工作AJAX代码。

首先我从我的表单中获取令牌

   var addAntiForgeryToken = function (data) {
            data.__RequestVerificationToken = $("[name='__RequestVerificationToken']").val();
            return data;
        };

amd 然后我调用我的方法

      $.ajax({
            type: "POST",
            url: "http://localhost:40428/controller/action",
            data: addAntiForgeryToken({ }),
            success: function (response) {

            }
        });

以上在我的controller中成功调用了下面的方法

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Test_Get()
    {
        ViewBag.Search = true;
        return View("Index");
    }

我已经尝试使用 axios 的是以下内容

    axios({
            method: 'post',
            url: 'http://localhost:40428/Meeting_Notes/Test_Get',
            data: addAntiForgeryToken({})
        });

我也试过手动设置 headers 但我仍然无法让它工作。

经过一番搜索后,我找到了一个简单的解决方案。首先创建controller并用HttpPost和ValidateAntiForgeryToken

装饰一下
[HttpPost]
[ValidateAntiForgeryToken]
public void Test_Axios(int id) { }

然后在使用 axios 调用控制器之前为 header 添加以下拦截器。这会将 header 定义为所有 axios api 调用的默认值

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

然后取回令牌

var token = document.querySelector('token, input').getAttribute('value');

然后使用 qs 库对带有令牌的调用进行字符串化(注意!是 Qs 而不是 qs!)

var request = Qs.stringify({ id: 22, __RequestVerificationToken: token });

如果你不想传递任何参数,那么你可以使用下面的

var request = Qs.stringify({ __RequestVerificationToken: token });

然后调用控制器方法

axios({
     method: 'post',
     url: "/controller/Test_Axios",
     data: request 
});

大功告成!您现在可以开始调用带有 [ValidateAntiForgeryToken] 属性的 mvc 5 控制器。