使用Fetch API发送__RequestVerificationToken并通过[ValidateAntiForgeryToken]操作接收]]

问题描述 投票:1回答:1

我想通过提取提交表单。控制器动作如下所示:

[HttpPost("new")]
[ValidateAntiForgeryToken]
public JsonResult NewUser(NewUserViewModel user)
{
    // code...
}

如您所见,我正在使用ValidateAntiForgeryToken。在客户端,我发现此jQuery代码有效:

$.ajax({
    url: window.location.pathname,
    type: 'POST',
    data: {
        Id: "1",
        UserName: "ajax",
        Password: "ajax",
        ConfirmPassword: "ajax",
        FullName: "ajax",
        Email: "[email protected]",
        Client: "ajax",
        Roles: ["ajax"],
        __RequestVerificationToken: document.querySelector('[name=__RequestVerificationToken]').value
    },
    success: function (response) {
        alert('Tókst');
    },
    error: function () {
        alert('tókst ekki');
    }
});

但是我想使用提取API,所以我尝试了此操作:

let response = await fetch(window.location.pathname, {
    method: 'POST',
    body: {
        Id: "1",
        UserName: "fetch",
        Password: "fetch",
        ConfirmPassword: "fetch",
        FullName: "fetch",
        Email: "[email protected]",
        Client: "fetch",
        Roles: ["fetch"],
        __RequestVerificationToken: document.querySelector('[name=__RequestVerificationToken]').value
    }
});

然后在下面处理响应。我本以为fetch调用与$ .ajax调用相同,但不起作用。

$。ajax调用一直执行到操作,但是fetch调用出现400错误。如果我从操作中删除[ValidateAntiForgeryToken],则提取调用确实起作用。

任何人都知道缺少什么,以便我可以通过fetch成功发布吗?

我想通过提取提交表单。控制器操作如下所示:[HttpPost(“ new”)] [ValidateAntiForgeryToken] public JsonResult NewUser(NewUserViewModel user){//代码...}当您...

javascript asp.net-mvc .net-core fetch-api
1个回答
0
投票

这就是我的工作方式。

© www.soinside.com 2019 - 2024. All rights reserved.