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

时间:2019-03-15 01:29:44

标签: asp.net-mvc paypal paypal-sandbox fetch-api

我正在将PayPal结帐与一个电子商务解决方案集成在一起,其中,在PayPal成功创建PayPal订单/付款后,我会执行一些服务器端处理,最终返回RedirectResult(付款URL失败或相应的成功)从我的控制器,回到客户端/前端。

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

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") ;

1 个答案:

答案 0 :(得分:1)

让我尝试重述您的问题

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

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

您将redirect设置为follow,这意味着在第一个请求之后(即在收到来自 /umbraco/surface/PayPalPayment/process),它将关注到网址/checkout/thank-you 因此,您在then()中得到的将是/checkout/thank-you

的响应

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

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

然后做:

  1. 修改后端以返回网址的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)});