我使用以下代码将数据发布到default2.aspx
页面。但当我跟踪default2.aspx
页面时,它运行了两次,我遇到了错误。
我的代码出了什么问题?
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();
}
答案 0 :(得分:1)
您正在呼叫该网页两次:
首先:
writer.Write(postData.ToString());
第二:
的Response.Redirect( “HTTP://本地主机:3629 / WebSite6 / Default2.aspx”);
这是一个非常有用的链接,可以解决您的问题:http://www.codeproject.com/KB/aspnet/ASP_NETRedirectAndPost.aspx
答案 1 :(得分:1)
当您关闭作者时,您将第一个帖子发布到default2,然后您的response.redirect导致第二个帖子。
if (writer != null)
writer.Close();