Url rewriting with http module in asp.net

Goldytech
Posted by in ASP.NET category on for Advance level | Views : 16954 red flag

In this post I show you what are httpmodule in asp.net and how can you develop your custom url rewriter solution. A post worth reading.
INTRODUCTION

I am highly impressed by Asp.net MVC framework. There are lot of exciting features into the framework but the one that excites me most is UrlRewriting module. Every url depends on the controller and its actions methods. The format of this url is something like this "{controllerclassname}/{actionmethodname}/{id}".  Moreover these pages doesn't physically exists on the hard drive.  Cool very cool. This feature impressed me so much that I decided to implement the same into my one of the asp.net web forms project. In this post I introduce you to http modules and how you can unleash their power and do miracles in your solutions.

HTTP MODULES

HttpModules are extremely powerful feature of asp.net. They act like listeners to the request that your asp.net application receives. Most of built in functionality of asp.net like output cache, session management, authentication and authorization are developed on HttpModules. An http module is a class which implements IHttpModule .  This interface has two methods Init and Dispose. The Init method is where you have to write the code to implement your custom functionality. The below listing shows the list of events that are available in the Init method.

  • AcquireRequestState
  • AuthenticateRequestState
  • AuthorizeRequestState
  • BeginRequest
  • EndRequest
  • Disposed
  • Error
  • PreRequestHandlerExecute
  • PostRequestHandlerExecute
  • PreSendRequestContent
  • PreSendRequestHeaders

I won’t get into the details of each and every event and when they are triggered. You can read more about them here. This article focuses on the url rewriting and to do so we will be using the BeginRequest event. This event is raised when a new request is arrived. This is the best place to override the default functionality. Just creating the custom class doesn't complete the work. You need to tell to the asp.net engine that I have a custom HttpModule. You can specify this in the web.config file under <httpModules> section. It should be written in the following format.

<add name ="YourmoduleName" type ="NamespaceName.ClassName,AssemblyName"/>

The next section in the post discusses my solution of url rewriting.

URL REWRITTING

This may not be a full fledge url rewriting solution. But this will help you to get started. Now let us talk about the solution I have two pages in my project

A Default page that displays the product categories and their description in the gridview. The category column is of type  HyperlinkField , clicking on this link will navigate to the Products page showing the relevant products that belongs to the category. A traditional solution would be of passing the querystring to the Products page and then displaying the records. But let us think how the asp.net mvc team thought, how about redirecting to the page which more user friendly something like “yourappname/Categories/Beverages”. Isn’t this more seo friendly and much pleasant than “yourappname/Products.aspx?Cn=Beverages”. So how do we do this ,well HttpModules can do it for you. Look at the sample code below.

public class myhttpModule :IHttpModule
    {
        private HttpApplication httpApp = null;
        #region IHttpModule Members

        void IHttpModule.Dispose()
        {
            throw new NotImplementedException();
        }

        void IHttpModule.Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
            httpApp = context;
        }

        /// <summary>
        /// This is the first event that triggers in request pipeline to IIS. Best place to manipulate the output that is send to client
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void context_BeginRequest(object sender, EventArgs e)
        {
            char[] seprator= {'/'};
            if (httpApp.Context.Request.Path.Contains("Categories")) //if the request url path consists of categories word then only we want to redirect otherwise normal processing should be done
            {
                string categoryName = httpApp.Context.Request.Path.Split(seprator, StringSplitOptions.None)[2]; //getting the required element from the array
                //redirecting to actual page with query string this will be sleath forwarding user wont notice query string in his browser address bar
                httpApp.Context.RewritePath("~/Products.aspx?cn=" + categoryName);
            }
        }

        #endregion
    }

As mentioned I use BeginRequest event and look for current requested page. Do some string manipulations and then using RewritePath method of the httpApplicaton context , I redirect to the actual page. But wait a minute will user be seeing this path or user friendly path in the address bar of the browser. The rewriter is smart enough it does a sleath forwarding so the user will never come to know what is the actual path the server has redirected to him.

CLOSURE

HttpModules can do amazing things for you. Download the sample code from here. You will be requiring Northwind sample database to run the solution. Please rename the file extension from .doc to .rar

Page copy protected against web site content infringement by Copyscape

About the Author

Goldytech
Full Name: Muhammad Afzal Qureshi
Member Level: Bronze
Member Status: Member
Member Since: 8/4/2009 10:58:17 PM
Country: India

http://goldytech.wordpress.com
Hello Everyone Myself Muhammad Afzal , aka GoldyTech. Thats my pen name. I reside in India and work as a solution Architect on .NET platform. I hope you must have enjoyed reading my blog. Please leave your comments or suggestions good or bad and help me to improve

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)