【问题标题】:Why RedirectToAction after Fetch POST request does not return new View()?为什么 Fetch POST 请求后 RedirectToAction 不返回 new View()?
【发布时间】:2020-06-08 13:00:06
【问题描述】:

我正在使用 Asp.Net Core 2.2

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

我在 JS 中的 Fetch:

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 调用?

【问题讨论】:

  • 听起来好像您希望将浏览器窗口重定向到 TransactionCompleted?如果是,...不,这不是 fetch() 的工作原理。您必须在 javascript 中处理结果并在客户端进行重定向。仅当您从浏览器的地址栏启动请求时,服务器端 RedirectToAction 才会起作用。
  • 你认为,如果我从fetch().then()调用一个JS函数,调用fetch GET someIActionResult,它应该可以完成这项工作吗?或者如何,以另一种方式,我应该在 Fetch 调用之后被重定向?
  • 你的 js 函数没有得到 IActionResult 而是 http 头。您的重定向当前位于您的 fetch() 函数内部。在 JavaScript 中,您“重定向”例如使用location.href。如果您不想对 url 进行硬编码,请在响应 f Checkout() 操作时返回 url。
  • @ChristophLütjen 我希望使用 Fetch API 获得更优雅的解决方案。无论如何,谢谢你,你让我明白该怎么做。

标签: javascript fetch asp.net-core-2.2


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2019-02-14
    • 2020-04-28
    • 1970-01-01
    • 2016-05-12
    • 2017-10-07
    • 2018-07-11
    相关资源
    最近更新 更多