如何包括@ Html.AntiForgeryToken()使用删除链接删除对象时 [英] How to include the @Html.AntiForgeryToken() when deleting an object using a Delete link
问题描述
我有以下 ajax.actionlink
这就要求一个删除的操作方法
删除的对象: -
i have the following ajax.actionlink
which calls a Delete action method
for deleting an object:-
@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
删除通话,以确保没有任何攻击者可以通过发送虚假的删除请求?
but is there a way to include @Html.AntiForgeryToken()
with the Ajax.actionlink
deletion call to make sure that no attacker can send a false deletion request?
BR
推荐答案
您需要使用 Html.AntiForgeryToken
帮助它设置一个cookie,并发出一个隐藏字段与相同的值。当发送AJAX请求您需要将此值添加到POST数据也是如此。
You need to use the Html.AntiForgeryToken
helper which sets a cookie and emits a hidden field with the same value. When sending the AJAX request you need to add this value to the POST data as well.
所以我会用一个正常的链接,而不是一个Ajax链接:
So I would use a normal link instead of an Ajax link:
@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(例如结束标记之前):
and then put the hidden field somewhere in the DOM (for example before the closing body tag):
@Html.AntiForgeryToken()
终于悄悄地AJAXify删除锚点:
and finally unobtrusively AJAXify the delete anchor:
$(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;
});
});
现在,你可以装饰你的删除
与 ValidateAntiForgeryToken
action属性:
Now you could decorate your Delete
action with the ValidateAntiForgeryToken
attribute:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
...
}
这篇关于如何包括@ Html.AntiForgeryToken()使用删除链接删除对象时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!