在 ajax - mvc5 中使用 AntiForgeryToken

Use AntiForgeryToken in ajax - mvc5

我该如何解决这个问题:

The required anti-forgery form field "__RequestVerificationToken" is not present.

我已经阅读了很多论坛,但找不到解决方案。似乎没有发送 AntiForgeryToken,但我不知道该怎么做。

在我看来我已经包括 @Html.AntiForgeryToken(),我的控制器有 [ValidateAntiForgeryToken]

 var http = new XMLHttpRequest();
        var url = "..@actionInAPP"
        var token = $('input[name="__RequestVerificationToken"]').val();
        var params =serialize(document.forms[@numForm]);
        console.log(params);

        http.open("POST", url, true);

           var form_data = new FormData(document.forms[@numForm]);
           return $.ajax({
             type: 'POST',
             url: url,
             contentType: false,
             processData: false,
             headers: { '__RequestVerificationToken': token },
             complete: function(){
                http.onreadystatechange = function () {
                     if (http.readyState == 4 && http.status == 200) {
                        window.location.reload();
                     }
                     if (http.readyState == 4 && http.status == 400) {
                        document.getElementById("@targetId").innerHTML = http.responseText;
                     }
                 }
                http.send(params);
            },
          });

信息保存在数据库中,但在我的浏览器中出现 500 错误 POST http://localhost:xxxx/xyz/Create 500(内部服务器错误)

这里有什么问题?

您可以将 __RequestVerificationToken 放在 jquery $ajax.data 字段中 并且,将您的表单数据放入 $ajax.data 字段,然后您的控制器将获取表单数据。

像这样

  $.ajax({
        url: $(this).data('url'),
        type: 'POST',
        data: { 
            __RequestVerificationToken: token, 
            someValue: 'some value' 
        },
        success: function (result) {
            alert(result.someValue);
        }
    });

include antiforgerytoken in ajax post ASP.NET MVC

我明白了!!! 我更改了 $ajax 并且效果很好

return $.ajax({
             type: 'POST',
             url, url,
             contentType: false,
             processData: false,
             data: form_data,
             Success: function(){
                http.send(params);
             },
            complete: function(http){
                if (http.readyState == 4 && http.status == 200) {
                    window.location.reload();
                }
                if (http.readyState == 4 && http.status == 400) {
                    document.getElementById("@targetId").innerHTML = http.responseText;
                }
           }
        });