views:

267

answers:

3

The follow code (running in ASP.Net 2.0) displays the contents of the requested URL twice. I only want it to display the contents of the requested URL once. I can't figure out what I'm doing wrong. The URL requested is returning XML and if I visit the URL directly, it works fine.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/xml";
request.ContentLength = postDataBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
requestStream.Close();

// get response and write to console
response = (HttpWebResponse) request.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
try {
   Response.Write(responseReader.ReadToEnd());
}
finally {
   responseReader.Close();
}
response.Close();
A: 

Where is that code being run from? This might be completely irrelevant but have you seen this article..?

http://ddkonline.blogspot.com/2008/02/aspnet-double-postback-bug-strikes.html

Ty
A: 

Your code looks good, so I don't think the problem is there... but what I would suggest is the following:

1) Maybe the error is on the URL's other end... so try hitting Google and see if the returned content is good or not.

2) Put a breakpoint at the "responseReader.ReadToEnd()" spot, and see if what's coming out of there is good.

3) If this code above is in an ASPX page... are you making sure to call "Response.End();" after you're last line of code? (not "resposne.close()", but "Response.End()").

Timothy Khouri
A: 

I found the problem. It's not with the above code at all, but with the page being called. The page I was calling was inherited from a class whose Page_OnInit method contained the following line: "MyBase.OnLoad(e)", which caused the Page_OnLoad method to be executed twice. Obviously, it should have been MyBase.OnInit(e) instead. I didn't catch it because when I tested the page directly I had to temporarily remove the inheritance from the class because of some other code that would've have prevented me from testing the page directly.

I will now put on my "Dunce" hat and retreat to the corner for a time out. Thanks anyway for the help.

chief_wampum

related questions