Andrea Azzola

Tips and Techniques for Lifestyle Design

Issues With AJAX and a Custom HttpModule

Posted on [Permalink]

My web app needs to catch every non-existent path as a search string, because I'm implementing an HttpModule that handle URLs in a SEO friendly way:

But the AJAX script module (a.k.a. "ScriptModule") decides to quit on me. So I add the following module:

<add name="ScriptModule" 
    type="System.Web.Handlers.ScriptModule, System.Web.Extensions, ..." />
<add name="MyModule" type="MyModule"/>

Then Internet Explorer (js debug enabled) decides it was the right time for firing fire some fancy javascript errors, like "AJAX Framework failed to load....". No problem, back to fixer mode... and this snippet is the final, working piece of snippet art:


public class MyModule : IHttpModule
  public MyModule()

  private void Application_OnAfterProcess(Object source, EventArgs e)
    HttpApplication application = (HttpApplication)source;
    HttpContext context = application.Context;

    if (context.Request.Headers["x-microsoftajax"] == null)
      if ((!System.IO.File.Exists(application.Request.PhysicalPath)) &&
        (!application.Request.Url.ToString().Contains(".axd")) &&
          string newUrl = "~/Search.aspx?q="
            + context.Server.UrlEncode(application.Request.Url.Segments.Last());

  #region IHttpModule Members

  void IHttpModule.Init(HttpApplication context)
    context.PostResolveRequestCache += 
        (new EventHandler(this.Application_OnAfterProcess));

Basically it intervenes at a specific part of the Request handle (AfterProcess) and just if a certain header is found then excludes the AJAX web services from the search, so they can be dealt with in the classic fashion.