【发布时间】:2015-07-21 12:30:46
【问题描述】:
我不知道如何在 ajax 中使用 AntiForgeryToken。
我在 SO 上找到了以下答案,但它们对我不起作用:
- jQuery Ajax calls and the Html.AntiForgeryToken()
- include antiforgerytoken in ajax post ASP.NET MVC
- How to make ajax request with anti-forgery token in mvc
这是我的代码 html:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.TextBoxFor(model => model.UserName, new { @class = "form-control", id = "UserName", placeholder = @CMS.Resources.Resource.UserName })
@Html.PasswordFor(model => model.Password, new { @class = "form-control", id = "Password", placeholder = @CMS.Resources.Resource.Password })
<button id="LoginButton" class="k-button" type="submit">@CMS.Resources.Resource.Signin</button>
}
JavaScript:
$('#LoginButton').click(function (e) {
if ($('form').valid()) {
var data = { UserName: $('#UserName').val(), Password: $('#Password').val() };
var token = $('[name=__RequestVerificationToken]').val();
var headers = {};
headers["__RequestVerificationToken"] = token;
$.ajax({
type: 'POST',
traditional: true,
data: JSON.stringify(data),
cache: false,
headers: headers,
dataType: 'json',
url: '@Url.Action("LoginPanel", "Account")',
contentType: "application/json; charset=utf-8",
success: function (status) {
},
error: function (status) {
alert(status);
}
});
}
e.preventDefault();
});
控制器:
[HttpPost, ValidateAntiForgeryToken]
public JsonResult LoginPanel(LoginModel model)
{
LoginStatus status = new LoginStatus();
if (HttpContext.Request.IsAjaxRequest())
{
if (ModelState.IsValid)
{
....
}
}
return Json(status, JsonRequestBehavior.AllowGet);
}
以及其他尝试过的 JavaScript 代码模式。通过将值 __RequestVerificationToken 放在标头或数据中。错误总是一样的:
所需的防伪表单字段“__RequestVerificationToken”不存在。
谢谢。
【问题讨论】:
标签: jquery ajax model-view-controller antiforgerytoken