Tuesday, May 06, 2008

How to patch ASP.Net Ajax in order to work on servers that add stuff to your page automatically

Thanks for Raheel for presenting me this problem and the opportunity to fix it.

As you may know from a previous post of mine, Ajax requests differ from normal requests. At the Page level, the rendered content is changed to reflect only the things that changed in the UpdatePanels and the format is different from the usual HTML and it is also very strict. Any attempt to blindly add things to the string sent from the server will result in an ugly alert error. And who does indiscriminately add ugly content to your Ajax requests? "Free" servers that inject commercials in your pages!

So, what can you do? Patch the Ajax engine to remove the offending ads. Here is a simple example for a server that added crap at THE END of the content, crap that did not contain any '|' characters. This is important, as the patch looks for the last '|' character and removes all the things after it.

C# Code

private void LoadApplyPatch()
ScriptManager sm = ScriptManager.GetCurrent(Page);
if (sm == null) return;

string script =@"
if (window.Sys&&Sys.WebForms&&Sys.WebForms.PageRequestManager) {
Sys$Net$WebRequestExecutor$get_responseData=function() {
if (arguments.length !== 0) throw Error.parameterCount();
if (!this._responseAvailable) {
throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_responseData'));
if (!this._xmlHttpRequest) {
throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_responseData'));

var content=this._xmlHttpRequest.responseText;

// this is the added code, the rest is taken
// from the ASP.Net Ajax original code
var index=content.lastIndexOf('|');
if (index<content.length-1)

return content;

Page.GetType(), "adMurderer", script, true);


Dicas de Código TI Blog said...

Unfortunally I'm still getting the error :(
My site is hosted at goddady.
I added your code at the Page_Load(). Am I missing something?

My page also has a masterpage. I did put the code to the masterpage Page_Load but the error persists.

Any ideas? THANK YOU!


Siderite said...

Well, I recommend you intercept the ajax calls with something like Fiddler and see what is added and where. As I said in the blog post, the patch is only good for hosting that adds stuff ONLY at the end of the content and ONLY if the stuff that it adds does not contain the '|' character in it.