ورود

View Full Version : مشکل AntiForgeryToken با Ajax



shahrooz_tk
یک شنبه 20 اردیبهشت 1394, 19:11 عصر
سلام
من توی فرمم از AntiForgeryToken استفاده کردم از اونجایی ام که فرمم ایجکسی هست با مشکل مواجه شدم و این ارور رو میده:

The required anti-forgery form field "__RequestVerificationToken" is not present.



کدهام به این شکله:

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() };
$.ajax({
type: 'POST',
data: JSON.stringify(data),
dataType: 'json',
url: '@Url.Action("LoginPanel", "Account")',
contentType: "application/json; charset=utf-8",
success: function (status) {

},
error: function (status) {
alert(status);
}
});
}
e.preventDefault();
});



controller:

[HttpPost, ValidateAntiForgeryToken]
public JsonResult LoginPanel(LoginModel model)
{
LoginStatus status = new LoginStatus();
if (HttpContext.Request.IsAjaxRequest())
{
if (ModelState.IsValid)
{

}
}
return Json(status, JsonRequestBehavior.AllowGet);


}



کلی گشت و گذار کردم روش های مختلفی بود واسه قرار دادن مقدار RequestVerificationToken در headers مثل کد زیر که هیچ کدوم جواب ندادن.


$('#LoginButton').click(function (e) {
if ($('form').valid()) {
var data = { UserName: $('#UserName').val(), Password: $('#Password').val() };
var token = $('[name=__RequestVerificationToken]').val();
$.ajax({
type: 'POST',
cache: false,
data: JSON.stringify(data),
headers: { "__RequestVerificationToken": token },
dataType: 'json',
url: '@Url.Action("LoginPanel", "Account")',
contentType: "application/json; charset=utf-8",
success: function (status) {

},
error: function (status) {
alert(status);
}
});
}
e.preventDefault();
});



دوستان کسی منو راهنمایی کنه ممنون می شم.
تشکر

sanay_esh
دوشنبه 21 اردیبهشت 1394, 09:35 صبح
سلام
این لینک (http://stackoverflow.com/questions/4074199/jquery-ajax-calls-and-the-html-antiforgerytoken) را دنبال کنید.