开发者

why HttpWebRequest runs the target page twice?

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?

str开发者_如何学编程ing 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();
    }


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜