Writing SEO friendly url using HttpHandlers in ASP.NET

SheoNarayan
Posted by in ASP.NET category on for Intermediate level | Views : 29561 red flag
Rating: 5 out of 5  
 2 vote(s)

In general it is recommend to not use querystring in the url as search engines doesn'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. However in this article, I am going to show you how to rewrite url using ASP.NET built in HttpHandler.
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.

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 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.




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


Step 1 - Create a HttpHandler

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

namespace UrlHandlerNameSpace
{
/// <summary>
/// Demo url HttpHandler
/// </summary>
public class DemoUrlHandler: IHttpHandler
{
/// <summary>
/// Process my requet
/// </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 handle my request and send 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 request (*), I have specified that this handler should serve all kinds of the request.
path specifies the path, when requested my hand;er 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 chard 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 comes 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 purpose 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.




Step 4 - Create a page (showArticle.aspx) to Show artilces

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 url and you will see 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 givne much more weightage than single page with diifferent querystring value.



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 little amount of code.

Thanks and happy coding !!!
Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Parasu on: 8/30/2009
Hi narayan,

Extraordinary article, Great. I tried this URL rewrite using
above sample code, its works fine. I have question/doubt
whatever it is, how could we say this kind of rewritten URL is SEO friendly? Basically I’m having little bit knowledge in
SEO, ok.

In the above sample code, we are using two aspx pages such as
1. Default.aspx and
2. showArticle.aspx

By click the (Article) link from default.aspx page, it will be
redirected to showArticle.aspx with rewritten URL (Modified
URL with querystring) using HttpHandler. Based on the
query string we can get data (Article content) from the
database, right. So there is no physical file (.aspx like
article1.aspx) stored in any place where to load in the
showArticle.aspx


Without Article1.aspx file how Search engine index that
particular page? Or it’s possible to store article content
(large data) in the database.

If so, how search engine indexing that kind pages (above
sample code scenario).

For example, I posted the below article in
www.dotnetfunda.com

What is windows service? How to create windows service
using C#.net?

Can you tell me whether its (article) stored as .aspx page or
stored in the database. If database means how search
engine index this page?

Could you please clarify these doubts?

Appreciated for your help.
-paras



Posted by: SheoNarayan on: 8/30/2009
Hi Parasu,

Thanks for your appreciation and feedback.

Now to answer your question, all contents are stored in the database and based on the url, code access the code from the database and shows that articleid contents.

Without a physical file, search engine will index the page as whenever article1.aspx url is given in the address bar, you are seeing a valid data coming from the server.

Hope this helps your question.

Thanks and regards,
Posted by: Vuyiswamb on: 2/16/2010
nice this is Exactly what i want. I will test it when i get home and give you a results of it.

Posted by: Umeshdwivedi on: 4/13/2011 | Points: 25
Dear Sir
this is good artical can you send in zip file on my email
sheelu.pandit@gmail.com

Login to post response

Comment using Facebook(Author doesn't get notification)