如何发布数据并重定向到外部页面?

3

我在提交数据和重定向到外部URL方面遇到了麻烦。该外部URL为在线支付网关,仅接受使用POST方法提交的表单。

像下面这样的简单html表单将无任何问题地工作:

<html>
<body>
<form action="externalpage.url" method="post">
<input type="hidden" name="name1" value="1234">
<input type="hidden" name="name2" value="abcd">
<input type="submit" value="Submit Form">
</form>
</body>
</html>

但在我的情境下,当用户点击我 ASPX 页面上的按钮时,我需要先进行一些服务器端处理,例如创建一个 NameValueCollection 对象,然后再将其重定向到支付网关。我尝试使用此链接中的示例:http://www.codeproject.com/Articles/37539/Redirect-and-POST-in-ASP-NET,但由于某种原因页面无法重定向到外部 URL。下面这行代码似乎没有起到任何作用。
page.Controls.Add(new LiteralControl(strForm));

在线支付!它是https网址吗?http://www.terminally-incoherent.com/blog/2008/05/05/send-a-https-post-request-with-c/ - Damith
4个回答

1
我想我已经解决了这个问题。以下是我的做法。
创建一个中间页面,例如DoPost.aspx。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Post Form</title>
    <script>
        function PostData() {
            document.getElementById("form1").submit();
        }
    </script>
</head>
<body onload="PostData()">
    <form id="form1" runat="server">
    <div>
        <asp:Literal ID="ltrPostData" runat="server"></asp:Literal>
    </div>
    </form>
</body>
</html>

然后在代码后台,

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var url = "external.url";
        form1.Action = url;
        ltrPostData.Text = "Create <input type='hidden' name='data name' value='data value' /> html controls from Request.QueryString() and assign the string value to the Literal control's Text property.";
    }
}

在 Submit.aspx 页面上,按钮点击事件发生的地方,
//assume that the NameValueCollection object has already been created and populated  
var redirectUrl = string.Format("{0}?{1}", "DoPost.aspx", BuildQueryString(data));
Response.Redirect(redirectUrl, true);

public static string BuildQueryString(NameValueCollection data)
{
    // create query string with all values
    return string.Join("&", data.AllKeys.Select(key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(data[key]))));
}

因此,实际上,即使我们需要通过第二个页面,我们仍然可以使用Response.Redirect()将数据传递给外部链接。简而言之,Submit.aspx [GET] => DoPost.aspx [Post] => 网关。

0

0

-1

1
由于 Response.Redirect 使用 GET 方法,任何使用 GET 提交的数据都将被网关拒绝,非常遗憾 :( - woodykiddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接