Rico
Rico

Reputation: 1298

ASP.net Post with redirect?

Basically I want to take a URLString and break out all variables and their values and Post them to another page with a redirect to taht page.. How do i pull this off without having a form and actuall submitting etc...

This is what i got..

   string url = "http://www.blah.com/xyz.aspx";


        StringBuilder postData = new StringBuilder();

        postData.Append("CustomerID=" + HttpUtility.UrlEncode("Hello Rico") + "&");
        postData.Append("FirstName=" + HttpUtility.UrlEncode("HelloFirstName"));
        //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());
            writer.Flush();

            HttpWebResponse WebResp = (HttpWebResponse)request.GetResponse();

            //Now, we read the response (the string), and output it.   
            Stream Answer = WebResp.GetResponseStream();
            StreamReader _Answer = new StreamReader(Answer);
            Response.Write(_Answer.ReadToEnd());

        }
        finally
        {
            if (writer != null)
                writer.Close();
        }   

Upvotes: 5

Views: 3821

Answers (3)

annakata
annakata

Reputation: 75794

I'm not sure this is the right strategy - have you considered either HttpModules for manipulating requests or Server.Transfer for internal redirection?

Upvotes: 1

Frazell Thomas
Frazell Thomas

Reputation: 6111

What is it that you need the page you're redirecting the user toward to do? Your best option is to use Session Variables to pass the data between pages on Redirection unless you care to preserve the form that was initially passed to the page.

You can use code such as the following to add the information to a session item.

Session.Item("CustomerID") = "CustomerID=" & ID.ToString

Upvotes: 0

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120937

Since you cannot redirect and post at the same time, your only option is to render an html page with a form that is submitted on page load. Unless you can make the receiver accept the parameters in the url of course. If it is an asp.net page you want to "post" to, it should not really matter if you send data in the querystring, unless of course you are sending massive amounts of data.

Remember that redirecting, is the same as telling the browser to "go to this page instead". This information is in the http header that you return. Therefore, there is not a lot of overhead in rendering a form that auto submits.

Upvotes: 2

Related Questions