Using IHttpModule to 301 redirect, C-Sharp.


A ThatsIT Solutions Tutorial

The IHttpModule is a class that intercepts requests before they hit the website; it gives you a chance to redirect before the websites knows about the request. You need to tell the web.config about the IHttpModule and the class itself sites anywhere in the website itself.

Web.Config

First here is the code for the web.config assuming the website has a namespace of PerthSeoCompany and the IHttpModule is called ReWrita.

<system.webServer>
.........
<modules runAllManagedModulesForAllRequests="true">
<add name="ReWrita" type="PerthSeoCompany.ReWrita" />
</modules>
.........
</system.webServer>

The IHttpModule Class

Next we have the code for out IHttpModule. We place our redirect logic in the Application_BeginRequest method

This code is in C-sharp, don't panic we have a Visual Basic version also. See Using IHttpModule, Visual-Basic

public class ReWrita : IHttpModule
{

    public static String ModuleName
    {
        get { return "ReWrita"; }
    }


    public void Init(HttpApplication application)
    {
        application.BeginRequest +=
            (this.Application_BeginRequest);
        application.EndRequest +=
            (this.Application_EndRequest);
    }

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

        String fullOrigionalpath = context.Request.Url.ToString().ToLower();
        String newPath = string.Empty;
        const string www = "www.perthseocompany.com.au";
        const string nonWww  = "perthseocompany.com.au";

        if (context.Request.Url.Host.Equals(www))
        {
            newPath = fullOrigionalpath.Replace( www, nonWww);
            context.Response.Status = "301 Moved Permanently";
            context.Response.AddHeader("Location", newPath);
        }
    }

    private void Application_EndRequest(Object source, EventArgs e)
    {


    }

    public void Dispose() { }
}