我有以下ajax.actionlink
调用Delete action method
来删除对象: -
@if (!item.IsAlreadyAssigned(item.LabTestID))
{
string i = "Are You sure You want to delete (" + @item.Description.ToString() + ") ?";
@Ajax.ActionLink("Delete",
"Delete", "LabTest",
new { id = item.LabTestID },
new AjaxOptions
{ Confirm = i,
HttpMethod = "Post",
OnSuccess = "deletionconfirmation",
OnFailure = "deletionerror"
})
}
但是有没有办法让@Html.AntiForgeryToken()
包含Ajax.actionlink
删除调用,以确保没有攻击者可以发送错误的删除请求?
BR
答案 0 :(得分:16)
您需要使用Html.AntiForgeryToken
帮助器来设置cookie并发出具有相同值的隐藏字段。发送AJAX请求时,您还需要将此值添加到POST数据中。
所以我会使用普通链接而不是Ajax链接:
@Html.ActionLink(
"Delete",
"Delete",
"LabTest",
new {
id = item.LabTestID
},
new {
@class = "delete",
data_confirm = "Are You sure You want to delete (" + item.Description.ToString() + ") ?"
}
)
然后将隐藏字段放在DOM中的某个位置(例如在关闭正文标记之前):
@Html.AntiForgeryToken()
最后不引人注意地AJAX化删除锚:
$(function () {
$('.delete').click(function () {
if (!confirm($(this).data('confirm'))) {
return false;
}
var token = $(':input:hidden[name*="RequestVerificationToken"]');
var data = { };
data[token.attr('name')] = token.val();
$.ajax({
url: this.href,
type: 'POST',
data: data,
success: function (result) {
},
error: function () {
}
});
return false;
});
});
现在,您可以使用Delete
属性装饰ValidateAntiForgeryToken
操作:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
...
}
答案 1 :(得分:2)
通过Bronx修改答案:
$.ajaxPrefilter(function (options, localOptions, jqXHR) {
var token, tokenQuery;
if (options.type.toLowerCase() !== 'get') {
token = GetAntiForgeryToken();
if (options.data.indexOf(token.name)===-1) {
tokenQuery = token.name + '=' + token.value;
options.data = options.data ? (options.data + '&' + tokenQuery)
: tokenQuery;
}
}
});
的答案
function GetAntiForgeryToken() {
var tokenField = $("input[type='hidden'][name$='RequestVerificationToken']");
if (tokenField.length == 0) { return null;
} else {
return {
name: tokenField[0].name,
value: tokenField[0].value
};
}
编辑 抱歉 - 意识到我在这里重新发明轮子SO asp-net-mvc-antiforgerytoken-over-ajax/16495855#16495855