Whidbey Cross Page Posting: Avoiding the Ugly Response.Write
Note: this entry has moved.
Quick Catchup: you may have heard about the new upcoming Cross Page Posting feature in ASP.NET Whidbey, in a nutshell: you will be able to post from page A to page B and while executing in Page B do some cool things like accessing the control tree for page A.
I was having dinner the other night with my gf and we where talking about *I don’t remember exactly what* when one sleeping thread in my head popped up and suddenly told me: “What about if the posting page uses Response.Write, that will be cause a mess!”.
Not having paid much attention to this feature before (read: not having run Reflector through it) I was pretty sure that if both pages were sharing the same HttpContext (which sounded logical to me) and the posting page called Response.Write to write its UI for example, then, when posted to another page, the target page UI will get all messed up with the posting page UI. Best of all this didn’t look like a bug at all, this was only good news, another excellent reason for people to finally start cleaning up calls to Response.Write in their code.
So, I quickly wrote the 3 lines of code required to test this scenario and hit Ctrl-F5.
I first browsed to –lets call it– Page “A” which included some garbage written out by calls to Response.Write. Then I clicked a button on Page “A” to cross post to Page “B” and expected Page “B” output to include the previous garbage… so far… no luck… Page “B” output was not including this… disappointing… :-(
At this point I started thinking that someone (read: the ASP.NET team) may have considered this before (just a year or two maybe? :-)) and included some workaround to make the life of developers using Response.Write much easier.
It was time for “the tool” to enter scene. It didn’t took me more than a minute or two to find out what was really happening, and yes, someone had thought about this before…
What is happening here is that before executing the posted page (Page “A”) from the target page (Page “B”), ASP.NET is cleverly switching the writer used by the HttpResponse instance with a dummy one, using a new internal (yes internal, sorry) method whose signature is:
internal TextWriter SwitchWriter(TextWriter writer);
After the posted page (Page “A”) has finished executing (and their controls are ready to be accessed by the target Page “B”) ASP.NET will switch again HttpResponse’s writer to the *real* writer this time thus allowing Page “B” to properly output whatever it needs to.
This is just an example of Whidbey helping the reputation of some ASP.NET developers :-)