In Asp.Net when you develop a data-driven website, to display different sort of data in a single page you usually use query strings on to the aspx page and pass parameters. (exapmple: products.aspx?catetory=book). Its not easy to remember for the user, if he wants to directly see the particular product page. URLs should be short, easy to type and visually show the structure of the site. We can get a well arranged and structured URL from URL rewriting.
Another main reason is SEO (Search Engine Optimization). URL rewriting also improves your search engine rank as most of search engines like Google, Bing, Yahoo use your URL’s keyword to index your site. Suppose somebody is searching for the keyword ” ASP.NET books”, now its a higher chance to get in search result for the keyword if your page is URL rewritten and have the keyword “Asp.Net books” instead of just a query string with numerical id.
Static URL Rewriting in Asp.NET
Static URL rewriting in asp.net is very easy to setup. If you have small number of pages in your website you can use static URL rewriting.
You just need to edit your web.config file and add some lines under tag.
You can add mapping rules in web.config file for your all aspx pages. Now if you navigate to http://yourwebsite.com/My-Home-Page your Default.aspx page will be processed.
By this method you can make your URLs stable, you can map any of your page to a fix URL.
The static URL rewriting is good for small websites. If you have so many pages in your website and dynamic pages also, static method will not apply there. So we need some dynamic mechanism of URL rewriting.
Dynamic URL Rewriting In ASP.NET
To accomplish Dynamic URL Rewriting, we have to Implement HttpModule. Rather than writing your own HttpModule for this task, I would suggest you to use pre built HttpModules available on the web for fee that will make it a very easy and handy task. You can download it from UrlRewriter.net or just download UrlRewriter.dll .
Now follow these steps
- Open your website project in Visual Studio
- Add reference to downloaded Intelligencia.UrlRewriter Dll file
- Now open web.config file and add following code just under the tag
- Now add UrlRewriter mapper HttpModule under the tag
- Now we can add rules for rewriting under tag and after closing tag as
As a short example we have a Default.aspx page that takes a query string “page” with page name. We will display the current page that is passed through query string (/Default.aspx?page=Home-Page).
Now to rewrite the query string as /home/home-page we will add following rule :
Below is the full web.config file configuration:
Full source code of Default.aspx
Source code of Default.aspx.cs
Now compile and run the website. Your static and dynamic URL rewriting is done.