使用MVC2 ActionResult,如何将(Post)重定向到另一个站点

时间:2011-01-07 19:21:10

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

我有一个页面收集数据和'POST'到另一个站点。我可以将他的网站网址放在表单标记的操作中,但我想在切换网站之前将信息记录在我的数据库中。到目前为止,在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();

有没有人知道如何完成此操作并使用正确的'return'变量将此数据发布到其他网站。

我根据下面的回复编辑了代码段。

2 个答案:

答案 0 :(得分:0)

POST已经发生了,所以不会有一个适合你的灵丹妙药(即一个简单的ActionResult)。由于您正在服务器上处理POST响应,因此您需要自己重新创建对目标服务器的POST请求。要做到这一点,您需要利用HttpWebRequestthis answer。{从HttpWebRequest收到回复后,您需要传回该回复,可能是通过ContentResult。总而言之,这将是非平凡的,但它是可能的。

<强>更新: 根据您的代码段,我会尝试添加以下内容:

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

答案 1 :(得分:0)

另一种选择是将表单操作指向其他站点,并在提交表单之前对服务器执行ajax发布。这比用HttpWebRequest打中间人要容易得多。

相关问题