c# - asp.net mvc 5.0 中的 ValidateAntiForgeryToken - 如何使用 JSON 和 ajax 传递对象数组
问题描述
似乎该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;
},
解决方案
最终使用FormCollection
它你可以一般地将任何东西传递给控制器。
推荐阅读
- airflow - 气流基本身份验证导致登录页面上出现“重定向过多”
- python - 大数的python除法自动上限
- android - 如何使用改造来解析带有属性的简单 XML?
- python - 基于 Pandas 数据框拆分的列值列表
- django - 如何创建从一个表指向同一个表的一对多关系?
- windows - 为目录/视图/主题/machiko/skins 中的所有文件夹和子文件夹设置 CHMOD 777!(视窗)
- java - 在从 Firestore (Android) 检索哈希映射值时需要帮助
- python - 如果从 python shell 运行,inspect.getsourcelines(object) 会显示 OSError,但如果从文件运行则不会出现错误
- html - IE11 中使用 flexbox 的布局不正确
- ios - 在swift iOS中计算高字节和低字节?