Response.Redirect with POST instead of Get?

后端 未结 14 963
离开以前
离开以前 2020-11-22 04:04

We have the requirement to take a form submission and save some data, then redirect the user to a page offsite, but in redirecting, we need to \"submit\" a form with POST, n

14条回答
  •  灰色年华
    2020-11-22 04:29

    HttpWebRequest is used for this.

    On postback, create a HttpWebRequest to your third party and post the form data, then once that is done, you can Response.Redirect wherever you want.

    You get the added advantage that you don't have to name all of your server controls to make the 3rd parties form, you can do this translation when building the POST string.

    string url = "3rd Party Url";
    
    StringBuilder postData = new StringBuilder();
    
    postData.Append("first_name=" + HttpUtility.UrlEncode(txtFirstName.Text) + "&");
    postData.Append("last_name=" + HttpUtility.UrlEncode(txtLastName.Text));
    
    //ETC for all Form Elements
    
    // Now to Send Data.
    StreamWriter writer = null;
    
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";                        
    request.ContentLength = postData.ToString().Length;
    try
    {
        writer = new StreamWriter(request.GetRequestStream());
        writer.Write(postData.ToString());
    }
    finally
    {
        if (writer != null)
            writer.Close();
    }
    
    Response.Redirect("NewPage");
    

    However, if you need the user to see the response page from this form, your only option is to utilize Server.Transfer, and that may or may not work.

提交回复
热议问题