Asp.net mvc 如何在MVC4中使用JSON post测试AntiForgeryToken
我用MVC4 visual studio 2012将Json发布到控制器。。。我已经成功地将json数据和AntiForgeryToken一起传递给控制器,但我不知道如何准确地测试它是否真的在“AntiForgeryToken的正确性”工作。此外,我还尝试在客户端的uu RequestVerificationToken代码中添加9999,以查看它是否在服务器端进行验证,并且它确实进行了验证!!!。我的猜测是,如果我是正确的,就不应该这样做????这是我的密码Asp.net mvc 如何在MVC4中使用JSON post测试AntiForgeryToken,asp.net-mvc,json,antiforgerytoken,simplemembership,Asp.net Mvc,Json,Antiforgerytoken,Simplemembership,我用MVC4 visual studio 2012将Json发布到控制器。。。我已经成功地将json数据和AntiForgeryToken一起传递给控制器,但我不知道如何准确地测试它是否真的在“AntiForgeryToken的正确性”工作。此外,我还尝试在客户端的uu RequestVerificationToken代码中添加9999,以查看它是否在服务器端进行验证,并且它确实进行了验证!!!。我的猜测是,如果我是正确的,就不应该这样做????这是我的密码 <script type="t
<script type="text/javascript">
$(document).ready(function (options) {
$('#id_login_submit').click(function () {
var token = $('input[name=__RequestVerificationToken]').val();
//var token = $('input[name=__RequestVerificationToken]').val()+"99999";
// alert("token :: "+token);
var _authetication_Data = { _UserName: $('#u1').val(), _Password: $('#p1').val(), "__RequestVerificationToken": token }
$.ajax({
type: "POST",
url: "/Account/ProcessLoginRequest",
data: JSON.stringify({ model: _authetication_Data }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert(response);
}
});
});
});
是的,你可以。。。但您可以尝试使用
serialize()
方法。大概是这样的:
$.ajax({
type: "POST",
url: "/Account/ProcessLoginRequest",
data: $("#your_form_id").serialize(),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert(response);
}
});
当您使用serialize
方法时,这会将表单
标记中的所有元素序列化为一个数据数组,类似于{field:value,field2:value2,field3:value3}
,并且标记将是隐藏的输入,因此,它将位于序列化结果上
有关更多信息,请参阅文档:它适合我,实际上我没有使用表单,这是我的代码: 查看代码: 控制器方法,只需使用阿片属性签名: [ValidateAntiForgeryToken] 公共JsonResult JSONEVIARSMS(字符串电话号码、字符串电话号码)
旁注:请确保您始终将活动挂在表单提交上,而不是按按钮。这是因为您仍然可以提交表单,但在文本输入时按Enter键。
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult ProcessLoginRequest(LoginModel model)
{
string returnString = null;
if (ModelState.IsValid && WebSecurity.Login(model._UserName, model._Password, persistCookie: false))
{
returnString = "user is authenticated";
}
else
{ returnString = "user not authenticated"; }
return Json(returnString, JsonRequestBehavior.AllowGet);
}
$.ajax({
type: "POST",
url: "/Account/ProcessLoginRequest",
data: $("#your_form_id").serialize(),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert(response);
}
});
var token = $('input[name=__RequestVerificationToken]').val();
$.post(url, { Telefono: telefono, MensajeSMS: mensajeSMS, __RequestVerificationToken : token }, ...............