MVC3, .Net 4 및 VS2010을 실행하고 있습니다. 문제를 설명하기 위해 다음 샘플 프로젝트를 수행했습니다.Anti Forge 토큰 및 Ajax JSON 포스트가 작동하지 않습니다.
내 컨트롤러 코드
namespace AntiForgeAjaxTest.Controllers
{
public class IndexController : Controller
{
public ActionResult Index()
{
MyData d = new MyData();
d.Age = 20;
d.Name = "Dummy";
return View(d);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(MyData data)
{
NameValueCollection nc = Request.Form;
return View(data);
}
protected override void ExecuteCore()
{
base.ExecuteCore();
}
}
}
내보기 및 자바 스크립트 코드 여기에 내가 두 버튼이
@model AntiForgeAjaxTest.Models.MyData
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
@using (Html.BeginForm("Index", "Index"))
{
@Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>@Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>@Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function() {
$('#myButton').click(function() {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
alert(JSON.stringify(myObject));
$.ajax({
type: 'POST',
url: '/Index/Index',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(myObject),
success: function (result) {
alert(result);
},
error: function (request, error) {
alert(error);
}
});
});
});
</script>
</body>
</html>
는, 첫 번째 양식 게시물을 트리거, 두 번째는 아약스 게시물을 트리거합니다. 양식 게시는 제대로 작동하지만 Ajax 서버는 그렇지 않습니다. 서버는 이미 내 JSON에 토큰을 포함 시켰음에도 불구하고 A required anti-forgery token was not supplied or was invalid.
이라고 불평합니다.
내 코드에 어떤 문제가 있습니까?
@nemesv이 게시물을 보았습니다. 거기에 질문을했지만 아직 답변이 없습니다. – hardywang
그럼이 답변이 충분하지 않았습니까? http://stackoverflow.com/a/7603172/538387 – Tohid