Tuesday, November 29, 2005

Custom HTTP Modules

Custom HTTP Modules

HTTP Modules provides an opportunity to examine each incoming and outgoing request before request processing.
A typical use of HTTP module is URL rewriting on the basis of content of URL string. For example if i want to convert URL like "mywebproject/ashish/default.aspx" into "mywebproject/default.aspx?user=ashish" or vice-versa.

Creating custom HTTP Modules:

  • Make a class for implementing your custom module and implement IHttpModule Interface.
  • Add event handlers for BeginRequest and EndRequest events
  • Register your custom HTTP Module using web.config
Make a class and adding Event Handlers:
 public class UrlMapperModule : IHttpModule
{
private EventHandler onBeginRequest;

public UrlMapperModule()
{
onBeginRequest = new EventHandler(this.HandleBeginRequest);
}

void IHttpModule.Dispose()
{
}

void IHttpModule.Init(HttpApplication context)
{
context.BeginRequest += onBeginRequest;
}


private void HandleBeginRequest( object sender, EventArgs evargs )
{
// Now check every request
string requestUrl = app.Context.Request.Url.PathAndQuery;
}
}
Registering Custom HTTP Module in web.config:











No comments: