gpt4 book ai didi

javascript - 为什么 Fetch POST 请求后 RedirectToAction 不返回 new View()?

转载 作者:行者123 更新时间:2023-11-28 03:08:26 26 4
gpt4 key购买 nike

我正在使用Asp.Net Core 2.2

我不明白为什么在 Fetch POST 调用之后,我的 POST IActionResult 没有重定向到另一个操作及其 View ?

我在 JS 中的获取:

window.onload = function () {
var requestToken = document.getElementsByName("__RequestVerificationToken")[0].value
fetch('http://localhost:53801/User/Checkout', {
method: 'post',
headers: {
"X-ANTI-FORGERY-TOKEN": requestToken,
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify({
token: 'sometoken',
payerID: 'someid',
amount: price,
users: usersQty,
years: yearsQty
})
}).catch(function (err) {
console.log(`error: ${err}`);
});
}

我的发布操作:

[HttpPost]
[Authorize]
public async Task<IActionResult> Checkout([FromBody] TransactionCompletedModel transaction)
{
AppUser user = await _userManager.GetUserAsync(User);
if (user != null)
{
if (user.PremiumExpiring == null || user.PremiumExpiring < DateTime.UtcNow)
{
user.PremiumExpiring = DateTime.UtcNow.AddYears(1); //if not yet have full access
}
else
{
user.PremiumExpiring = user.PremiumExpiring.AddYears(1); //if already have full access
}

await _userManager.UpdateAsync(user);
}

return RedirectToAction(nameof(TransactionCompleted));
}

以及应该返回新 View 的方法,但它没有:

[Authorize]
public IActionResult TransactionCompleted()
{

return View();
}

执行 Fetch 调用后,我在浏览器控制台中收到:

XHR GET http://localhost:53801/User/TransactionCompleted [HTTP/1.1 200 OK 724ms]

据我了解,我的 RedirectToAction 没有任何问题,那么为什么 public IActionResult TransactionCompleted() 不返回/重新加载新 View ,只是我坚持使用旧 View 查看,Fetch 调用在哪里执行?

最佳答案

根据 Christoph Lütjen 的建议,我必须修改我的 Controller POST 操作以返回 URL:

[HttpPost]
[Authorize]
public async Task<IActionResult> Checkout([FromBody] TransactionCompletedModel transaction)
{
//other rows without change

return Ok("TransactionCompleted?token=" + transaction.Token);
}

现在,我的 Fetch API 调用从 POST 调用获取对 Checkout 的响应,并将其用于重定向:

var requestToken = document.getElementsByName("__RequestVerificationToken")[0].value
fetch('http://localhost:53801/User/Checkout', {
method: 'post',
headers: {
"X-ANTI-FORGERY-TOKEN": requestToken,
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify({
token: 'sometoken',
payerID: 'someid',
amount: price,
users: usersQty,
years: yearsQty
})
})
.then((response) => { return response.json(); })
.then((result) => { window.location = result })
.catch(function (err) {
console.log(`error: ${err}`);
});

关于javascript - 为什么 Fetch POST 请求后 RedirectToAction 不返回 new View()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60383686/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com