0

I use following code for posting data to default2.aspx page. but when I trace the default2.aspx page it runs twice and I encounter error. What's wrong with my code?

string url = "http://localhost:3629/WebSite6/Default2.aspx";
        StringBuilder postData = new StringBuilder();
        postData.Append("first_name=" + HttpUtility.UrlEncode("Raymond") + "&");
        postData.Append("last_name=" + HttpUtility.UrlEncode("Sanaz"));
        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("http://localhost:3629/WebSite6/Default2.aspx");

Default2.aspx:

protected void Page_Load(object sender, EventArgs e)
    {
     s= Request.Form["first_name"].ToString();
    }
Raymond Morphy
  • 2,464
  • 9
  • 51
  • 93

2 Answers2

1

You are calling the page twice:

First:

writer.Write(postData.ToString());

Second:

Response.Redirect("http://localhost:3629/WebSite6/Default2.aspx");

This is a very helpful link for your problem: http://www.codeproject.com/KB/aspnet/ASP_NETRedirectAndPost.aspx

Vaibhav Garg
  • 3,630
  • 3
  • 33
  • 55
1

When you close the writer, your issuing the first post to default2, then your response.redirect is causing the second post.

if (writer != null)                
writer.Close();
WooHoo
  • 1,912
  • 17
  • 22
  • But i wanna show default2.aspx, If I remove `Response.Redirect("http://localhost:3629/WebSite6/Default2.aspx");` I can not show it in my browser. what should I do? – Raymond Morphy Aug 02 '11 at 11:00
  • Could you give me a bit more background of what your trying to achieve? – WooHoo Aug 02 '11 at 11:14
  • I have two different websites, the first website just has a registration link but the registration from is in second website. Now I want to when user click on registration link in first website the first website sends some parameter to my registration form in second website and after that user completed the registration form in second website My web site redirect the user to first website with some paramaters. something like online payment. – Raymond Morphy Aug 02 '11 at 11:33
  • 1
    Could the second website post its values to the first website say website1.default and then redirect to website1.defaultNewPage? If that doesnt work check out this http://stackoverflow.com/questions/5179/how-do-i-post-and-then-redirect-to-an-external-url-from-asp-net – WooHoo Aug 02 '11 at 11:52