如何从 redirect.aspx.cs 重定向到 AngularJS 页面?
结论
redirect.aspx.cs 不能直接调用 AngularJS 的 $state.go()。前者运行在服务器端,AngularJS UI-Router 则运行在浏览器中。
可以按以下流程处理:
- ASP.NET 接收 payment gateway 发来的 POST 回调。
- 服务器验证支付结果并保存相关数据。
- 使用
Response.Redirect()将浏览器重定向到 AngularJS 路由。 - 通过 URL 查询参数传递
payment_reference,再由 AngularJS 使用$stateParams读取。
配置 AngularJS State
需要将 payment_reference 声明为 URL 查询参数,不能只把它放在非 URL 类型的 params 中:
$stateProvider.state('RedirectPage', {
url: '/RedirectPage?payment_reference',
templateUrl: 'App/LeaseRequest/PaymentRedirect.html',
controller: 'PaymentRedirect'
});
在控制器中读取该参数:
app.controller('PaymentRedirect', function ($scope, $stateParams) {
$scope.paymentReference = $stateParams.payment_reference;
console.log($stateParams.payment_reference);
});
在 redirect.aspx.cs 中重定向
下面的代码适用于 ASP.NET Framework Web Forms:
using System;
using System.Web;
public partial class redirect : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string paymentReference = Request.Form["payment_reference"];
if (string.IsNullOrWhiteSpace(paymentReference))
{
Response.StatusCode = 400;
Response.Write("Missing payment_reference.");
Context.ApplicationInstance.CompleteRequest();
return;
}
// 在这里验证 payment gateway 的签名及支付结果。
// 验证成功后,再保存支付状态并执行跳转。
string encodedReference = HttpUtility.UrlEncode(paymentReference);
string targetUrl =
"/RedirectPage?payment_reference=" + encodedReference;
Response.Redirect(targetUrl, false);
Context.ApplicationInstance.CompleteRequest();
}
}
浏览器最终访问的地址类似:
/RedirectPage?payment_reference=PAYMENT-12345
AngularJS 控制器可以通过以下代码取得参数值:
$stateParams.payment_reference
需要使用 HttpUtility.UrlEncode() 对参数进行编码,因为 reference number 中可能包含 +、/、=、& 等影响 URL 解析的字符。
如果项目使用 Hash 路由
如果 AngularJS 应用没有启用 HTML5 Mode,实际路由通常位于 # 后面。此时应重定向到 AngularJS 应用的入口页面,例如:
string encodedReference = HttpUtility.UrlEncode(paymentReference);
string targetUrl =
"/index.html#/RedirectPage?payment_reference=" + encodedReference;
Response.Redirect(targetUrl, false);
Context.ApplicationInstance.CompleteRequest();
对应的地址类似:
/index.html#/RedirectPage?payment_reference=PAYMENT-12345
如果应用启用了 HTML5 Mode,则可以使用前面的普通路径:
/RedirectPage?payment_reference=PAYMENT-12345
不过,服务器必须配置 SPA fallback,确保直接请求 /RedirectPage 时仍会返回 AngularJS 的入口页面,否则刷新页面或重定向后可能出现 404。
更安全的处理方式
不能只根据 URL 中的 payment_reference 判断支付是否成功。查询参数由用户控制,可能被修改或伪造。
更稳妥的流程如下:
redirect.aspx接收 payment gateway 的 POST 数据。- 验证 gateway 提供的签名、金额、订单号和支付状态。
- 将验证后的结果保存到数据库或服务器端会话中。
- 重定向到 AngularJS 页面。
- AngularJS 使用 reference number 或一次性 token 向后端查询最终支付状态。
例如,服务器可以只传递一个短期有效的一次性 token:
string targetUrl =
"/RedirectPage?token=" + HttpUtility.UrlEncode(oneTimeToken);
这样可以避免将敏感的支付响应直接暴露在 URL、浏览器历史记录和服务器日志中。
还要注意,URL 中 # 后面的内容不会发送到服务器。因此,payment gateway 的 POST 回调仍须指向 redirect.aspx 这类服务器端地址,不能直接 POST 到 AngularJS 的 Hash 路由。
备注:内容仅供参考。
