Saturday, June 4, 2011

Clean Code by "Uncle Bob" Martin
A must for any developer with an interest in producing better code. Read Reviews or Buy Now

URL Rewriting with URLRewriter.Net

URL Rewriting has lots of benefits, listing its main benefits

  • SEO Friendly URL
  • Secured URL
  • No need to change bookmark with change in site structure.

Before URL Rewriting my URL looks like
http://localhost:2661/URLRewrite2/DynamicPage.aspx?MyTitleId=1

After URL Rewriting URL is changed to

http://localhost:2661/URLRewrite2/Article/Asp-Net-website-paths-1.aspx


Lets Understand URL Rewriting with Simple Example

A Website displaying articles list in a gridview on clicking the article link, it will display dynamically generated article content.

Before URL Rewriting when you mouse-over 1st Article Link, "Asp.net Website Path" it uses query string to display the article content.


Dynamic page display Querysting, before URL Rewriting.



After URL Rewriting we will achieve how SEO Friendly URL is used to display article content.


Now, lets understand how we can achieve it.

For URL Rewriting we are using URLRewriter.Net which is available free. Download URLRewriter.Net

Step-by-Step Explanation

Step 1: Download Binary Files for URLRewriter.Net

Step 2: Add Reference to Binary Files, Right click project "Add Reference" and add binary files.


Step 3: Update Web.Config File to make URLRewriter.Net works.
<configuration>

<configSections>
<section name="rewriter"
requirePermission="false"
type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
configSections>

<system.web>

<httpModules>
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
httpModules>

system.web>

<system.webServer>

<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule" />
modules>

<validation validateIntegratedModeConfiguration="false" />

system.webServer>

<rewriter>
<rewrite url="~/Article/(.+)-(.+).aspx" to="~/DynamicPage.aspx?MyTitleId=$2"/>
rewriter>

configuration>


Step 4: Adding Function to Generate SEO Friendly URL from given Title

public static string GenerateURL(object Title, object strId)
{
string strTitle = Title.ToString();

#region Generate SEO Friendly URL based on Title
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');

strTitle = strTitle.ToLower();
char[] chars = @"$%#@!*?;:~`+=()[]{}|\'<>,/^&"".".ToCharArray();
strTitle = strTitle.Replace("c#", "C-Sharp");
strTitle = strTitle.Replace("vb.net", "VB-Net");
strTitle = strTitle.Replace("asp.net", "Asp-Net");

//Replace . with - hyphen
strTitle = strTitle.Replace(".", "-");

//Replace Special-Characters
for (int i = 0; i < chars.Length; i++)
{
string strChar = chars.GetValue(i).ToString();
if (strTitle.Contains(strChar))
{
strTitle = strTitle.Replace(strChar, string.Empty);
}
}

//Replace all spaces with one "-" hyphen
strTitle = strTitle.Replace(" ", "-");

//Replace multiple "-" hyphen with single "-" hyphen.
strTitle = strTitle.Replace("--", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("-----", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("--", "-");

//Run the code again...
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');
#endregion

//Append ID at the end of SEO Friendly URL
strTitle = "~/Article/" + strTitle + "-" + strId + ".aspx";

return strTitle;
}


Step 5: Changing DataBinder.Eval Function in .Aspx Page to reflect changes in URL of Grid.
Note: Learn more about DataBinder.Eval Function


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" Width="788px">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<Columns>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:HyperLink ID="hlTitle" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Title")%>' NavigateUrl='<%#GenerateURL(DataBinder.Eval(Container.DataItem,"Title"),DataBinder.Eval(Container.DataItem,"Id"))%>'>asp:HyperLink>
ItemTemplate>
asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDesc" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Description")%>'>asp:Label>
ItemTemplate>
asp:TemplateField>
Columns>
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
asp:GridView>


Now, Lets Check the stuff so far developed.

Assigning SEO Friendly URL in to grid.


On clicking URL inside grid it will point to Dynamically Generated Page with SEO Friendly URL, rather than QueryString.


Things to consider while URL Rewriting.

Problem 1: Page Postback, will turns User Friendly URL into Original URL.
Problem 2: CSS, Image Files pointing to URL Rewriting Page won't work, as they might be pointing with absolute path.

Problem 1: Page Postback for Page displaying URL Rewritten URL
Page Postback of Page displaying User friendly URL will turns into original state when same page postback occurs. In our example, I am adding one button and trying to make Page Postback. You will notice that Page Postback will turns the User Friendly URL into original URL containing QueryString.


For Resolving Page PostBack problem for Page displaying URL Rewritten URL

This article is inspired from Scott's URL Rewritten article. Adding two files as mentioned by scott. If you are developing code in VB download files from Scott's article, else for C# download files with Sourcecode at the end of this article.



Now, lets test the Page Postback by clicking on Button, you will notice this time, URL remains the same.




Problem 2: Image Display Problem
Now, lets display image on for this page and lets observe what problem we may run into. I have added following line to display image, but it won't works.
<img src="Images/article.gif" />


Resolve Problem, by refrencing file from root.
<img src="../Images/article.gif" />



Download Source-Code for URL Rewriting

http://dotnetguts.blogspot.com/2008/07/url-rewriting-with-urlrewriternet.html

1 Comment:

  1. Bruce Lee said...
    It's very cool, thx for ur work. But I am experimenting with URL Rewriting. The first time it displays with the correct url. After performing any event handling, the form posts back, and then it has wrong url. Like the page url is http://devweb.tsgdomain.com/nphnewdemo/Enewsletter/68 and when i click url button then it gives wrong url http://devweb.tsgdomain.com/nphnewdemo/Enewsletter/popup.aspx?name=dev-test-please-review-it instead of this url http://devweb.tsgdomain.com/nphnewdemo/popup.aspx?name=dev-test-please-review-it.
    Please suggest some answers to why this is happening (and how I can make this work correctly).

Post a Comment