Javascript post 请求回调,从 .NET MVC 控制器重定向

Javascript post request callback, redirect from .NET MVC controller

我正在将 PayPal 结账与电子商务解决方案集成在一起,在 PayPal 成功创建 PayPal order/payment 后,我进行了一些服务器端处理,最终 returns RedirectResult (使用 URL 表示付款失败或成功)从我的控制器返回到 client/frontend.

我在下面有以下代码,并希望它能自动重定向,但没有发生重定向。

paypal.Buttons({
    createOrder: function (data, actions) {
        return actions.order.create({
            intent: "CAPTURE",
            purchase_units: [{
                amount: {
                    value: '5.20',
                }
            }]
        });
    },
    onApprove: function (data, actions) {
        return actions.order.capture().then(function (details) {
            return fetch('/umbraco/surface/PayPalPayment/process', {
                method: 'post',
                redirect: 'follow',
                body: JSON.stringify({
                    OrderID: data.orderID,
                    PayerID: data.payerID,
                }),
                headers: {
                    'content-type': 'application/json'
                }
            });
        }).catch(error=>console.log("Error capturing order!", error));
    }
}).render('#paypal-button-container');

如果我使用下面的代码明确重定向,那么操作就会执行。

onApprove: function (data, actions) {
        return actions.order.capture().then(function (details) {
            return fetch('/umbraco/surface/PayPalPayment/process', {
                method: 'post',
                redirect: 'follow',
                body: JSON.stringify({
                    OrderID: data.orderID,
                    PayerID: data.payerID,
                }),
                headers: {
                    'content-type': 'application/json'
                }
            }).then(function () { window.location.replace('https://www.google.co.uk') });
        }).catch(function (error) {
            console.log("Error capturing order!", error);
            window.location.replace('https://www.bbc.co.uk');
        });
    }

基本上,我想知道为什么获取重定向不遵循从我的控制器返回的重定向。完全完整的控制器重定向:

return new RedirectResult("/checkout/thank-you") ;

让我试着重新表述一下你的问题

您想知道为什么 浏览器 在您做出 fetch 后没有重定向 - 尽管 fetch api 响应 是 RedirectResult

原因很简单,您在 fetch 中发出了请求,这意味着您正在发出 ajax 请求(因此浏览器不会更改)

你将 redirect 设置为 follow,这意味着在第一个请求之后(即在从 /umbraco/surface/PayPalPayment/process),它将跟随到url /checkout/thank-you 所以,您在 then() 中得到的将是 /checkout/thank-you

的响应

总的来说,它确实遵循了响应,但可能不是您预期的方式(遵循 ajax 请求,而不是浏览器更改页面)

如果您想要重定向到特定页面,请在成功调用后调用 /umbraco/surface/PayPalPayment/process

然后做:

  1. 将您的后端修改为 url 的 return JsonResult 而不是 RedirectResult
return Json(new {redirectUrl = "/checkout/thank-you"});
  1. 使用then重定向
// other code omitted

.then(function (response) { return response.json(); })
.then(function (data) {window.location.replace(data.redirectUrl)});