javascript - 为什么 Fetch POST 请求后 RedirectToAction 不返回 new View()?
问题描述
我正在使用Asp.Net Core 2.2
我不明白为什么在 Fetch POST 调用之后,我的 POST IActionResult 没有重定向到另一个操作及其视图?
我在 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}`);
});
}
我的 POST 动作:
[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));
}
以及应该返回新视图的方法,但它没有:
[Authorize]
public IActionResult TransactionCompleted()
{
return View();
}
执行 Fetch 调用后,我在浏览器控制台中收到:
XHR GET http://localhost:53801/User/TransactionCompleted [HTTP/1.1 200 OK 724ms]
据我了解,我的 没有任何问题RedirectToAction
,那么为什么public IActionResult TransactionCompleted()
不返回/重新加载新视图,只是我坚持执行 Fetch 调用的旧视图?
解决方案
根据Christoph Lütjen的建议,我不得不修改我的控制器 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}`);
});
推荐阅读
- python - 使用 python 和 beautifulsoup 对 Google Ads 进行网页抓取
- java - 我不知道为什么我的下一个 If 语句只是我最后的手段!JAVA
- c# - 后台线程和对话框
- php - 使用 PHP 和 Amazon AWS EC2 的会话
- powershell - Powershell 脚本审核远程桌面用户登录
- google-apps-script - Google App Script - 如果单元格与字符串中的条件匹配,则更改单元格的颜色
- python - python Tkinter 破碎背景
- r - 下载 R 包时遇到问题:“*.o:文件格式无法识别”
- javascript - CSS 滚动捕捉 API?
- python - 如何在没有省略号的情况下打印所有 eli5.explain_weights() 结果?