簡體   English   中英

如何使用 MVC AntiForgeryToken 進行 AJAX 發布

[英]How to do an AJAX post with MVC AntiForgeryToken

如果我刪除了ValidateAntiForgeryToken屬性,這個刪除按鈕只會調用控制器方法。 如何更改其中任何一種方法以保留防偽令牌。 我假設 .NET 不相信這種刪除方式是安全的,並且會導致 AJAX 無法訪問控制器。 我想找到最安全的方式來發送刪除呼叫。

刪除按鈕 AJAX。

$("table").on("click", ".btn-delete", function (e) {
            var thisId = $(this).data('id');
            if (confirm("Are you sure you want to delete this item?")) {
                $.post('/AdminPortal/Client/Delete/', { id: thisId }, function (data) {
                    window.location.href = "/AdminPortal/Client/Index";
                });
            }
        });

刪除方法控制器

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Delete(string id)
{
    //add priv check here in the future
    var client = baseSvc.ClientRepo.GetById(long.Parse(id));
    if (client != null)
    {
        client.IsActive = false;
        baseSvc.ClientRepo.Save(client);
    }
    return RedirectToAction(nameof(Index), new { area = nameof(AdminPortal) });
 }

我的代碼中有以下內容:

全局 JavaScript 函數

// CSRF (XSRF) security
function addAntiForgeryToken(data) {
    //if the object is undefined, create a new one.
    if (!data) {
        data = {};
    }
    //add token
    var tokenInput = $('input[name=__RequestVerificationToken]');
    if (tokenInput.length) {
        data.__RequestVerificationToken = tokenInput.val();
    }
    return data;
};

在我的_Layout.cshtml中(某個地方,所以它在每個頁面上)

@Html.AntiForgeryToken()

用法:然后在進行 POST 之前,您可以調用該方法將令牌添加到您的數據中:

let data = addAntiForgeryToken({ id: thisId });
$.post('/AdminPortal/Client/Delete/', data, function (response) {
    window.location.href = "/AdminPortal/Client/Index";
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM