Issues with AJAX and a custom HttpModule

Posted by Andrea on 2005-06-18 17:32
My Web application needs to catch every non-existent path as a search string,
so I'm implementing an HttpModule that treats Url in this way:

  http://contoso.com/search-string

It maybe used also for SEO purpouses...

The point it's that I need the AJAX script module (a.k.a. "ScriptModule") working too.
If I simply add my custom module as following...

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

..then, Internet Explorer (js debug enabled) fires some javascript errors ("AJAX Framework failed to load....").
So I change my code... and that's the final, working, output.

using...

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")) &&
        (!application.Request.Url.ToString().Contains(".asmx")))
        {
          string newUrl = "~/Search.aspx?q="
            + context.Server.UrlEncode(application.Request.Url.Segments.Last());
          ...
          context.RewritePath(newUrl);
        }
     }
  }

  #region IHttpModule Members

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

As you could see, there are some specific filters.
Please note, this is only a draft, "provided as is with no warranties" ;).