【问题标题】:Using MVC2 ActionResult, how can I redirect (Post) to another site使用 MVC2 ActionResult,我如何重定向(发布)到另一个站点
【发布时间】:2011-01-07 19:21:10
【问题描述】:

我有一个收集数据并将“POST”发送到另一个站点的页面。我可以将他的站点 url 放在表单标签的操作中,但我想在切换站点之前将信息记录在我的数据库中。到目前为止,在 ActionResult 中我有:

    [HttpPost]
    public ActionResult MyPage(MyPageModel model)
    {
        if (ModelState.IsValid)
        {
            StoreDate(model.fld1, model.fld2)
            var encoding = new ASCIIEncoding();
            var postData = "";
            foreach (String postKey in Request.Form)
            {
                var postValue = Encode(Request.Form[postKey]);
                postData += string.Format("&{0}={1}", postKey, postValue);
            }
            var data = encoding.GetBytes(postData);

            // Prepare web request...
            var myRequest = (HttpWebRequest)WebRequest.Create("https://www.site2.com");
            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = data.Length;

            // Send the data.
            Stream newStream = myRequest.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Flush();
            newStream.Close();

有谁知道如何完成此操作并使用适当的“返回”变量将此数据发布到其他站点。

我已根据以下回复编辑了 sn-p。

【问题讨论】:

    标签: c# asp.net-mvc-2 post redirect


    【解决方案1】:

    POST 已经发生,所以不会有灵丹妙药(即简单的ActionResult)对您有用。由于您在服务器上处理 POST 响应,因此您需要自己重新创建对目标服务器的 POST 请求。为此,您需要利用HttpWebRequest 相对于this answer。从HttpWebRequest 获得响应后,您需要将该响应传回,可能通过ContentResult。总而言之,这将是不平凡的,但它是可能的。

    更新: 根据您的 sn-p,我会尝试添加以下内容:

    WebResponse res = myRequest.GetResponse();
    StreamReader sr = new StreamReader(res.GetResponseStream());
    string returnvalue = sr.ReadToEnd();
    return Content(returnValue);
    

    【讨论】:

    • 我曾经有过这个,但不知道接下来的步骤。我将如何从响应中构建 ContentResult?
    • @Randy,我已经用一个建议修改了我的答案。
    • 谢谢柯克,这正是我所缺少的。
    【解决方案2】:

    另一种选择是将表单操作指向另一个站点,并在提交表单之前将 ajax 发布到您的服务器。这比在 HttpWebRequest 中扮演中间人要容易得多。

    【讨论】:

    • 中间人是对的。这种问题对我来说总是很可疑。
    猜你喜欢
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    相关资源
    最近更新 更多