0

I have a page that collects data and 'POST's to another site. I could just put he site url in the action of the form tag but I would like to record the information in my database prior to switching sites. In the ActionResult so far I have:

    [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();

Does anyone know how to finish this and use the proper 'return' varient to have this post the data to the other site.

I have edited the snippet based on a response below.

Randy
  • 1
  • 2

2 Answers2

0

The POST has already happened, so there's not going to be a magic bullet (i.e. a simple ActionResult) that will work for you. Since you're handling the POST response on your server, you'll need to recreate the POST request to the target server yourself. To do that you'll need to leverage an HttpWebRequest vis a vis this answer. After getting the response back from the HttpWebRequest, you'll need to pass that response back, probably via a ContentResult. All in all, it will be non-trivial, but it is possible.

Update: Based on your snippet, I'd try adding the following:

WebResponse res = myRequest.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
return Content(returnValue);
Community
  • 1
  • 1
Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
0

Another option would be to point the form action at the other site and do an ajax post to your server before submitting the form. That would be much easier than playing man-in-the-middle with HttpWebRequest.

dotjoe
  • 26,242
  • 5
  • 63
  • 77