我想通过fetch提交表单。 Controller 操作如下所示:
[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: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2948434851694843485107405a" rel="noreferrer noopener nofollow">[email protected]</a>",
Client: "ajax",
Roles: ["ajax"],
__RequestVerificationToken: document.querySelector('[name=__RequestVerificationToken]').value
},
success: function (response) {
alert('Tókst');
},
error: function () {
alert('tókst ekki');
}
});
但是我想使用 fetch API,所以我做了这个尝试:
let response = await fetch(window.location.pathname, {
method: 'POST',
body: {
Id: "1",
UserName: "fetch",
Password: "fetch",
ConfirmPassword: "fetch",
FullName: "fetch",
Email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="52343726313a12343726313a7c3b21" rel="noreferrer noopener nofollow">[email protected]</a>",
Client: "fetch",
Roles: ["fetch"],
__RequestVerificationToken: document.querySelector('[name=__RequestVerificationToken]').value
}
});
然后在下面处理响应。 我本以为 fetch 调用与 $.ajax 调用相同,但它不起作用。
$.ajax 调用一直进行到操作,但 fetch 调用收到 400 错误。 如果我从操作中删除 [ValidateAntiForgeryToken],则 fetch 调用会起作用。
有谁知道缺少什么,以便我可以使用 fetch 成功发布此内容?
最佳答案
这就是我让它发挥作用的方法。
我在 Startup.cs 中添加了这一行:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAntiforgery(x => x.HeaderName = "X-ANTI-FORGERY-TOKEN");
...
}
然后我在获取请求的 header 中添加了“X-ANTI-FORGERY-TOKEN”:
let response = await fetch(form.action, {
body: JSON.stringify(this.Json),
method: form.method,
headers: {
"X-ANTI-FORGERY-TOKEN": document.getElementsByName("__RequestVerificationToken")[0].value,
"Content-Type": "application/json",
"Accept": "application/json"
}
});
现在它就像一个魅力。
关于javascript - 使用 Fetch API 发送 __RequestVerificationToken 并使用 [ValidateAntiForgeryToken] 操作接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57727595/