Javascript 使用Fetch API发送uu RequestVerificationToken,并使用[ValidateAntiForgeryToken]操作接收
我想通过fetch提交一份表格。控制器操作如下所示:Javascript 使用Fetch API发送uu RequestVerificationToken,并使用[ValidateAntiForgeryToken]操作接收,javascript,asp.net-mvc,.net-core,fetch-api,Javascript,Asp.net Mvc,.net Core,Fetch Api,我想通过fetch提交一份表格。控制器操作如下所示: [HttpPost("new")] [ValidateAntiForgeryToken] public JsonResult NewUser(NewUserViewModel user) { // code... } 如您所见,我使用的是ValidateAntiForgeryToken。 在客户端,我发现jQuery代码可以工作: $.ajax({ url: window.location.pathname, typ
[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: "ajax@ajax.is",
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: "fetch@fetch.is",
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");
...
}
然后,我在提取请求的头中添加了“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"
}
});
现在它就像一个符咒。可能是这样:)我已经找了好几个星期了,直到找到你,非常感谢我的朋友。这正是我需要的。请好好享受生活,因为你应得的,圣诞快乐!