使用ajax post时如何处理CSRF攻击?
我基本上想制作一个ajax帖子来发送一些stateId并从该州返回一些城市列表。
<form id="frmAjax" action="#">
@Html.DropDownList("states", (SelectList)ViewBag.States)
@Html.AntiForgeryToken()
</form>
我这样做的请求是这样的:
function PopulateTable() {
var x=$("#frmAjax").serialize();
$.ajax({
url: '@Url.Action("GetCities")',
type: 'POST',
dataType: 'json',
data: [1]
success: function (data) {
var target = $(".displayData tbody");
target.empty();
for (var i = 0; i < data.length; i++) {
target.append('<tr><td>' + data[i].Id + '</td><td>' + data[i].Name + '</td><td>' + data[i].Population+ '</td></tr>');
}
}
});
}
操作是这样的
[ValidateAntiForgeryToken]
public JsonResult GetCities([2])
{
var cities= new Service().GetCities(stateId);
return Json(classes);
}
我应该用什么来代替 [1] 和 [2] 以便它可以工作?我基本上希望这个 ajax 帖子与使用 AntiForgeryToken() 和 ValidateAntiForgeryToken 的常规帖子一样安全。 谢谢。
I basically want to make an ajax post to send some stateId and get back some list of cities from that state.
<form id="frmAjax" action="#">
@Html.DropDownList("states", (SelectList)ViewBag.States)
@Html.AntiForgeryToken()
</form>
I do the request like this:
function PopulateTable() {
var x=$("#frmAjax").serialize();
$.ajax({
url: '@Url.Action("GetCities")',
type: 'POST',
dataType: 'json',
data: [1]
success: function (data) {
var target = $(".displayData tbody");
target.empty();
for (var i = 0; i < data.length; i++) {
target.append('<tr><td>' + data[i].Id + '</td><td>' + data[i].Name + '</td><td>' + data[i].Population+ '</td></tr>');
}
}
});
}
The action is something like this
[ValidateAntiForgeryToken]
public JsonResult GetCities([2])
{
var cities= new Service().GetCities(stateId);
return Json(classes);
}
What should i put instead of [1] and [2] so it can work? I basically want this ajax post to be as secure as a regular post with AntiForgeryToken() and ValidateAntiForgeryToken.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你几乎就在那里:
然后:
这显然假设你使用视图模型(顺便说一下,你应该总是使用它)并且:
或者如果你不想使用视图模型(违反我的建议),请确保你提供一个这个弱类型助手的正确名称:
You were almost there:
and then:
this obviously supposes that you use a view model (which by the way you should always use) and:
or if you don't want to use view models (against my recommendation) make sure you provide a proper name to this weakly typed helper: