如何在ASP.NET MVC中不使用JavaScript/AJAX实现提交并重定向到外部网站?
在ASP.NET MVC中不使用JavaScript/AJAX提交数据并重定向到外部网站的实现方法
由于HTTP协议的限制,服务器无法直接发起POST请求的重定向。要实现提交数据到外部网站的需求,我们可以通过返回一个包含隐藏表单的视图,由浏览器完成POST提交操作。
实现步骤:
创建视图模型
定义一个用来存储目标URL和待提交数据的模型:public class ExternalPostViewModel { // 外部网站的目标提交地址 public string TargetUrl { get; set; } // 待提交的键值对数据 public Dictionary<string, string> FormData { get; set; } }控制器处理逻辑
在支付处理方法中,生成待提交的数据,然后返回对应的视图:public IActionResult ProcessPayment(CheckoutModel model) { var paymentGateway = new PaymentGatewayService(); // 生成支付网关需要的提交数据 var submitData = paymentGateway.PostPayment(paymentTransaction, selectedPaymentMethod); var postModel = new ExternalPostViewModel { TargetUrl = "https://外部支付网关地址", FormData = submitData }; return View("ExternalPost", postModel); }创建提交视图
创建名为ExternalPost.cshtml的视图,渲染包含所有隐藏字段的表单。若严格禁止JavaScript,保留手动提交按钮即可;若允许少量脚本实现自动跳转,可以添加自动提交逻辑:无JavaScript版本(手动提交):
@model ExternalPostViewModel @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>跳转中...</title> </head> <body> <form method="post" action="@Model.TargetUrl"> @foreach (var kvp in Model.FormData) { <input type="hidden" name="@kvp.Key" value="@kvp.Value" /> } <p>正在跳转至支付页面,请点击下方按钮继续:</p> <button type="submit">前往支付</button> </form> </body> </html>带自动提交脚本版本(接近自动重定向效果):
@model ExternalPostViewModel @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>跳转中...</title> <script> // 页面加载完成后自动提交表单 window.addEventListener('load', function() { document.querySelector('form').submit(); }); </script> </head> <body> <form method="post" action="@Model.TargetUrl"> @foreach (var kvp in Model.FormData) { <input type="hidden" name="@kvp.Key" value="@kvp.Value" /> } <p>正在跳转至支付页面,若未自动跳转请点击按钮:</p> <button type="submit">前往支付</button> </form> </body> </html>
原理说明
服务器处理完业务逻辑后,返回一个包含目标表单的HTML页面。浏览器加载该页面后,要么由用户手动触发表单提交,要么通过脚本自动提交,从而将数据POST到外部网站。这种方式完全符合HTTP协议规范,无需使用AJAX。
内容的提问来源于stack exchange,提问作者h3n
相关产品推荐
相关产品推荐

