【问题标题】:ValidateAntiForgeryToken in asp.net mvc 5.0 - how to pass array of objects with JSON and ajaxasp.net mvc 5.0 中的 ValidateAntiForgeryToken - 如何使用 JSON 和 ajax 传递对象数组
【发布时间】:2020-10-27 03:44:59
【问题描述】:

似乎ValidateAntiForgeryToken 属性会阻止数据在传递给MVC 控制器时被正确解析,当我删除ValidateAntiForgeryToken 属性但不能使用它时,下面的代码有效,控制器操作中的所有参数都是传递除了翻译数组。

请告知如何在使用ValidateAntiForgeryToken 属性时传递对象数组,这是否可能?

这是我的代码

C#

 [HttpPost]
 [ValidateAntiForgeryToken]
 public void AddComment( string code, string type, string ecomment, IEnumerable<CommentTranslation> translations) 
  {
            //do something later
   }

评论翻译是

public class CommentTranslation
    {
        public string LangId { get; set; }
        public string LangName { get; set; }
        public string Translation { get; set; }
    }

js

addComment: function (ecomment, type, translations) {


        var data = {           
                code: '',
                type: type,
                ecomment: ecomment,
                translations: translations
        };

        var url = 'CommentsAjax/AddComment';
        return comments.repository.postDataWithToken(data, url);
    },

  postDataWithToken: function (data, url) {
        
        return $.ajax({
            type: 'POST',
            traditional: true,
            contentType: 'application/x-www-form-urlencoded; charset=utf-8',
            data: comments.repository.addAntiForgeryToken(data),
            url: getServerPath() + url
        });
    }


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

【问题讨论】:

  • 您的 form 元素中有以下内容吗? @Html.AntiForgeryToken() 如果没有,那么你没有有效的令牌可以通过。

标签: c# jquery ajax asp.net-mvc-5 antiforgerytoken


【解决方案1】:

最终使用FormCollection,您可以将任何东西一般地传递​​给控制器​​。

【讨论】:

    猜你喜欢
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 2019-01-26
    相关资源
    最近更新 更多