首页 > 解决方案 > 为什么 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 调用的旧视图?

标签: javascriptfetchasp.net-core-2.2

解决方案


根据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}`);
            });

推荐阅读