我在使用 ajax 时遇到 AntiForgeryToken 问题。我正在使用 ASP.NET MVC 3。我尝试了以下解决方案jQuery Ajax 调用和 Html.AntiForgeryToken() https://stackoverflow.com/questions/4074199/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 required anti-forgery token was not supplied or was invalid.
当我放回属性时,消息仍然弹出。
有任何想法吗?
EDIT
防伪令牌是在表单内生成的,但我没有使用提交操作来提交它。相反,我只是使用 jquery 获取令牌的值,然后尝试使用 ajax 发布该值。
这是包含令牌的表单,位于顶部母版页:
<form id="__AjaxAntiForgeryForm" action="#" method="post">
@Html.AntiForgeryToken()
</form>
您错误地指定了contentType
to application/json
.
以下是其工作原理的示例。
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(string someValue)
{
return Json(new { someValue = someValue });
}
}
View:
@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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)