我有与ajax的AntiForgeryToken麻烦。我使用ASP.NET MVC 3.我尝试了解决方案在
jQuery Ajax calls and the Html.AntiForgeryToken().使用该解决方案,令牌现在正在传递:
var data = { ... } // with token,key is '__RequestVerificationToken'
$.ajax({
type: "POST",data: data,datatype: "json",Traditional: true,contentType: "application/json; charset=utf-8",url: myURL,success: function (response) {
...
},error: function (response) {
...
}
});
当我删除[ValidateAntiForgeryToken]属性只是为了看看数据(与令牌)是否作为参数传递到控制器,我可以看到,他们正在传递。但由于某种原因,A所需的反伪造令牌未提供或无效。消息仍然弹出时,我把属性回来。
有任何想法吗?
编辑
deforgerytoken是在表单内部生成的,但我没有使用提交操作来提交它。相反,我只是得到的令牌的值使用jquery,然后尝试ajax帖子。
这是包含令牌的表单,位于顶部母版页:
<form id="__AjaxAntiForgeryForm" action="#" method="post">
@Html.AntiForgeryToken()
</form>
您错误地将contentType指定为application / json。
这里有一个例子,这可能如何工作。
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(string someValue)
{
return Json(new { someValue = someValue });
}
}
视图:
@using (Html.BeginForm(null,null,FormMethod.Post,new { id = "__AjaxAntiForgeryForm" }))
{
@Html.AntiForgeryToken()
}
<div id="myDiv" data-url="@Url.Action("Index","Home")">
Click me to send an AJAX request to a controller action
decorated with the [ValidateAntiForgeryToken] attribute
</div>
<script type="text/javascript">
$('#myDiv').submit(function () {
var form = $('#__AjaxAntiForgeryForm');
var token = $('input[name="__RequestVerificationToken"]',form).val();
$.ajax({
url: $(this).data('url'),type: 'POST',data: {
__RequestVerificationToken: token,someValue: 'some value'
},success: function (result) {
alert(result.someValue);
}
});
return false;
});
</script>