我正在使用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));
}
和只应返回新View的方法,但没有:
[Authorize]
public IActionResult TransactionCompleted()
{
return View();
}
在执行Fetch调用后,我在浏览器控制台中收到:
XHR GEThttp://localhost:53801/User/TransactionCompleted[HTTP / 1.1 200 OK 724ms]
据我所知,我的RedirectToAction
没什么问题,所以为什么public IActionResult TransactionCompleted()
不返回/重新加载新视图,而只是停留在执行Fetch调用的旧视图上?
[[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}`);
});