Tuesday, September 25, 2007

Rewrite urls in asp.net (To make them search engine friendly)

Suppose you have urls that looks as that one

http://www.vic.bg/Default.aspx?c=29
http://www.vic.bg/Default.aspx?c=30
http://www.vic.bg/Default.aspx?c=31

but you want to looks like those:

http://www.vic.bg/Police.aspx
http://www.vic.bg/Students.aspx
http://www.vic.bg/Sport.aspx

without having actual pages.

You should add new IHttpHandler in your web.config file which dynamically will transform from one to another.

Step by step:

1. Add new library project.
2. Add new class and inherit PageHandlerFactory. That is .net handler that process .aspx files. We will add logic to rewrite pages and then will pass them to original handler

You can add much complex logic here for example transform one url to another with regular expression.


namespace VicHttpHandlers
{
public class VicRewriteUrlHandlerFactory : PageHandlerFactory
{
VirtualPathTableAdapter vpta = new VirtualPathTableAdapter();

Dictionary _pathMaps = new Dictionary();

public VicRewriteUrlHandlerFactory()
{
Vicove.VirtualPathDataTable dt = vpta.GetData();
foreach (Vicove.VirtualPathRow row in dt)
_pathMaps.Add(row.VirtualPath, row.RealPath);
}
#region IHttpHandler Members
VicRewriteUrlHandler handler = new VicRewriteUrlHandler();

public override IHttpHandler GetHandler(
HttpContext context,
string requestType,
string virtualPath,
string path)
{
if (_pathMaps.ContainsKey(HttpUtility.UrlDecode(context.Request.Url.PathAndQuery)))
{
context.RewritePath(_pathMaps[HttpUtility.UrlDecode(context.Request.Url.PathAndQuery)], false);
virtualPath = context.Request.Path;
path = context.Request.PhysicalPath;
}

return base.GetHandler(context, requestType, virtualPath, path);

}

#endregion
}
}

4. Change you web.config

<httpHandlers>
<add verb="*" path="*.aspx" type="VicHttpHandlers.VicRewriteUrlHandlerFactory, VicHttpHandlers" />