Click here to Skip to main content
Click here to Skip to main content

Writing SEO Friendly URL using HttpHandlers in ASP.NET

, 28 May 2011 GPL3
Rate this:
Please Sign up or sign in to vote.
In general, it is recommend to not use querystring in the URL as search engines don't rank those pages well and give very low priority. To avoid querystring there are several third party component that can be used like ISAPI, URL rewriter.

Introduction

HttpHandler is the low level Request and Response API to service incoming HTTP requests. All handlers implement the IHttpHandler interface. There is no need to use any extra namespace to use it as it contains in the System.Web namespace. Handlers are somewhat analogous to Internet Server Application Programming Interface (ISAPI) extensions.

Background

In this article, I am going to explain how to use HttpHandler to create a SEO friendly as well as user friendly URL. During this article, I will create two .aspx file, one HandlerUrl.cs class file. I am assuming here that I have to show a different article based on the id I get from the request. But I will not get the id as querystring but as part of the name of the page like article1.aspx or article2.aspx. Here 1 and 2 is my article id. I will extract it and send into my page (showarticle.aspx) using Server.Transfer method so that my URL in the browser will be like article1.aspx but internally it will be served as showarticle.aspx?id=1.

solution.GIF

I am going to show how to do this in a few steps.

(To get hundreds of real time .NET How to solutions, click here.)

Step 1 - Create an HttpHandler

Right click your App_Code folder and add a .cs file named HandlerUrl.cs and write the following code:

namespace UrlHandlerNameSpace
{
    /// <summary>
    /// Demo url HttpHandler
    /// </summary>
    public class DemoUrlHandler: IHttpHandler
    {
        /// <summary>
        /// Process my request
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            // get the requested page name like article1.aspx
            string strUrl = System.IO.Path.GetFileName(context.Request.RawUrl.ToString());

            // get the page name without extension eg. "article1"
            int len = strUrl.IndexOf(".");

            // as the length of "article" is 7 
            int sep = 7;

            // subtract the length of "article" word from the complete length 
            // of the page name to get the 
            // length of the id, as it may be 1, 100, 50000 
            // (1 character lonr or 3 chars long or may be 5 chars long)
            len -= sep;

            // now get the exact id
            string id = strUrl.Substring(sep, len); 

            // Now transfer the request to the actual page that will show the article 
            // based on the id
            HttpContext.Current.Server.Transfer("~/urlhandler/showArticle.aspx?id=" + id);
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    } 
}

As you can see, I have inherited IHttpHandler interface into DemoUrlHandler class file so I will have to implement two methods of it - ProcessRequest and IsReusable. ProcessRequest is the method that handles my request and sends the request using Server.Transfer to the showArticle.aspx specifying the id of as the querystring. I have done some calculations to extract the id from the name of the requested page.

Step 2- Add httpHandler into the web.config File

Go to your web.config file and add the handler for your request as below inside system.web tag.

  <httpHandlers>
      <add verb="*" path="article/article*.aspx" type="UrlHandlerNameSpace.DemoUrlHandler"/>
    </httpHandlers>

In the above code,

  • verb specifies whether the request will serve only GET or POST or all requests (*), I have specified that this handler should serve all kinds of the request.
  • path specifies the path, when requested my handler should take action. In this case, I have specified that my handler should act when my requested URL contains "article/article*.aspx". You can specify wild card characters too, like I have specified here. Notice "*" between "article" and ".aspx" characters. It means that I am instructing that my handler should act irrespective of whatever characters come after "article" word in my page name.
  • type specifies the URL handler class name preceded with namespace. Here, I have kept my handler class DemoUrlHandler inside UrlHandlerNameSpace namespace.

Step 3 - Create a Page (default.aspx) to List Different URLs

For testing purposes, I have created a default.aspx page that will list different URLs like article1.aspx, article2.aspx, article3.aspx, etc. as displayed in the picture below:

demourl.GIF

Step 4 - Create a Page (showArticle.aspx) to Show Articles

This page will show my article based on the querystring passed to it from my handler.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request["id"] != null)
            {
                // Call your function to get data from database based on the id
                // This is just a demo application so I am writing title based on the id

                string title = "Title for Article " + Request["id"].ToString();
                litPageTitle.Text = title;
                this.Title = title;
            }
        }
    } 

Now make the default.aspx page as startup page and run your demo project. You should see the page like default.aspx above, try clicking one of the URLs and you will see the corresponding page (below image). Notice the address bar in the picture below. The URL is "/article/article8.aspx" but internally this page is being served by showarticle.aspx with querystring as 8 (/urlhandler/showarticle.aspx?id=8). In this way, you are not showing querystring in the browser, your URL is neat and clean. This page will be understood by the search engines as a complete stand along page rather than a page with different querystring value and will be given much more weightage than a single page with different querystring value.

showarticle.GIF

Conclusion

To form a SEO friendly and user friendly URL, we don't need to use any third party component. Using ASP.NET HttpHandler, we can do it easily by writing a small amount of code.

Thanks and happy coding!!!

Read my many articles on www.DotNetFunda.com.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

Share

About the Author

Sheo Narayan
IT Funda Corporation
India India
Solution of .NET Problems - Get hundreds of .NET How to's
Follow on   Twitter

Comments and Discussions

 
QuestionQuestion Pinmemberanildiggiwal22-Jun-12 0:08 
AnswerRe: Question Pinmemberanildiggiwal17-Jul-12 1:06 
GeneralMy vote of 5 Pinmembervgirimtech10-May-12 23:17 
QuestionQuestion PinmemberRahul Rajat Singh24-Feb-12 1:55 
GeneralNo source code available can u send the source code.. PinmemberShaify8-Jun-11 18:47 
AnswerRe: No source code available can u send the source code.. PinmemberSheo Narayan8-Jun-11 18:51 
Generalthis is a bad solution Pinmemberdjpitagora1-Aug-08 1:27 
GeneralRe: this is a bad solution PinmemberSheo Narayan1-Aug-08 4:23 
GeneralIncreasing SEO Visibility PinmemberSteven Berkovitz3-Jul-08 4:26 
For even better SEO visibility, I use URL's in the format
 
ID-Article-Title.aspx.
 
In my HTTP handler (I'm actually just using a generic rewriter module that utilizes a regex for pattern matching), I just search for the first numeric component before the dash to get the article ID.
 
I've had good results with this.
 
-Steven

GeneralRe: Increasing SEO Visibility PinmemberSheo Narayan3-Jul-08 4:34 
GeneralRe: Increasing SEO Visibility Pinmemberexistenz_3-Jul-08 23:04 
GeneralRe: Increasing SEO Visibility PinmemberBrad Bruce28-May-11 7:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.141015.1 | Last Updated 28 May 2011
Article Copyright 2008 by Sheo Narayan
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid