URL Rewriting in ASP.NET using C#

A URL rewriting is very important when you are running a community website where user posts articles, forum messages in web sites.


URL Rewriting

A URL rewriting is very important when you are running a community website where user posts articles, forum messages etc. URL rewriting is the process of intercepting an incoming Web request and automatically redirecting it to a different URL. Discusses the various techniques for implementing URL rewriting.

For example

In this example we create a database table with title, description and author name. Title link will be create in the asp .net GridView control. when we click on the title link it will be redirect to the dynamic page.

Create a table in database named as Articletable. Table looks like this.

CREATE TABLE [dbo].[Articletable](

      [ID] [int] NOT NULL,

      [Title] [varchar](200) NULL,

      [Description] [varchar](400) NULL,

      [Author] [varchar](50) NULL

)

Inserting data in the articletable.

INSERT INTO Articletable VALUES(1,'How to validate dropdownlist in asp.net','Here, we will learn how to validate a DropDownList in ASP.NET.','Rohatash Kumar');

GO

INSERT INTO Articletable VALUES(2,'Introduction to .NET Assemblies in VB.NET',' Here is a comprehensive introduction to .NET assemblies.','sunil Kumar');

go

INSERT INTO Articletable VALUES(3,'BinaryReader and BinaryWriter classes in VB.NET','In this article I will explain about BinaryReader and BinaryWriter Classes in VB.NET.','Deepak Kumar');

 

go

INSERT INTO Articletable VALUES(4,'StreamWriter class in VB.NET','This article shows how to create a new text file and write a string to it.','Rohatash Kumar');

go

select * from articletable;

OUTPUT

databasetable

Table1

Now in ASP. NET

  1. Open Visual Studio.
  2. Add two webForm to your website, name it Gridview.aspx and dynamicpage.aspx.

Now drag and drop a GridView control from the Toolbox on the gridview.aspx page.

Gridview.aspx

The form looks like this.

gridview with property

Figure1

The ASP. NET code for the gridview.aspx page.

<form id="form1" runat="server">

   <div>   

       <h1>

       <span style="color: #009900">URL Rewriting</span></h1>

       <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

           BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"

           CellPadding="3" CellSpacing="2" Width="788px" Height="80px">

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

 

               <asp:TemplateField HeaderText="Author">

                   <ItemTemplate>

                        <asp:Label ID="lblauthor" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Author")%>' NavigateUrl='<%#GenerateURL(DataBinder.Eval(Container.DataItem,"Author"),

DataBinder.Eval(Container.DataItem,"Id"))%>'></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>

       &nbsp;

   </div>

   </form>

.CS code

 

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

 

public partial class _Default : System.Web.UI.Page

{

   protected void Page_Load(object sender,EventArgs e)

    {

        GridView1.DataSource = GetData();

        GridView1.DataBind();

    }

 

   

 

   public static string GenerateURL(object Title, object strId)

    {

       string strTitle = Title.ToString();

 

       //#region Generate SEO Friendly URL based on Title

  

        strTitle = strTitle.Trim();

        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");

        strTitle = strTitle.Replace(".","-");

       for (int i = 0; i < chars.Length; i++)

        {

           string strChar = chars.GetValue(i).ToString();

           if (strTitle.Contains(strChar))

            {

                strTitle = strTitle.Replace(strChar, string.Empty);

            }

        }

        strTitle = strTitle.Replace(" ","-");

 

        strTitle = strTitle.Replace("--","-");

        strTitle = strTitle.Replace("---","-");

        strTitle = strTitle.Replace("----","-");

        strTitle = strTitle.Replace("-----","-");

        strTitle = strTitle.Replace("----","-");

        strTitle = strTitle.Replace("---","-");

        strTitle = strTitle.Replace("--","-");

        strTitle = strTitle.Trim();

        strTitle = strTitle.Trim('-');       

        strTitle ="~/Article/" + strTitle +"-" + strId +".aspx";

 

       return strTitle;

    }

 

   private DataTable GetData()

    {

       string strConn = ("Data Source=.; uid=sa; pwd=Password$2; database=userinfo");

       SqlConnection conn =new SqlConnection(strConn);       

       SqlDataAdapter da =new SqlDataAdapter("select Id,Title,Description,author from Articletable", conn);

       DataSet ds = new DataSet();

        da.Fill(ds,"MyTestTable");

       return ds.Tables["MyTestTable"];

    }

}

 

 

dynamicpage.aspx

The form looks like this.


dynamicpage with gridview data


Figure2

The ASP. NET code for the dynamicpage.aspx page.

<form id="form1" runat="server">

   <div>

       <h1><img src="../Images/article.gif" />Article</h1>

       <b>Title:</b><asp:Label ID="lblTitle" runat="server" Text="Label" Font-Bold="true" ForeColor="blue"></asp:Label><br />

        AuthorName<b>:</b><asp:Label ID="lblauthor" runat="server" Text="Label"

           Font-Bold="true" ForeColor="blue"></asp:Label>

       <br />

       <br />

       <b>Description:</b><br />

       <asp:Label ID="lblDescription" runat="server" Text="Label"></asp:Label><br /><br />

       <br /><br />

       &nbsp;</div>       

   </form>

.CS code

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

 

public partial class DynamicPage : System.Web.UI.Page

{

   protected void Page_Load(object sender,EventArgs e)

    {

       if (Request.QueryString["MyTitleId"] != null)

        {

           string strId = Request.QueryString["MyTitleId"].ToString();

            DisplayArticle(strId);   

        }

    }

 

   private void DisplayArticle(string strId)

    {

       string strConn = ("Data Source=.; uid=sa; pwd=Password$2; database=userinfo");

       SqlConnection conn =new SqlConnection(strConn);       

       SqlDataAdapter da =new SqlDataAdapter("select Id,Title,Description,author from Articletable where Id=" + strId, conn);

       DataSet ds = new DataSet();

        da.Fill(ds,"Articletable");

        lblTitle.Text = ds.Tables["Articletable"].Rows[0][1].ToString();

        lblDescription.Text = ds.Tables["Articletable"].Rows[0][2].ToString();

        lblauthor.Text = ds.Tables["Articletable"].Rows[0][3].ToString();   

    }

   protected void Button1_Click(object sender,EventArgs e)

    {

 

    }

}

 

URLRewriter.dll

Now Add the reference of the URLRewriter.dll in the bin folder of the application witch is attached with the download file.

Add a image

Add Image in the images folder of the application that will be display with the title of dynamic page at run time witch is also attached with the download file.

Now run the application and test it.

gridview with database record

Figure3

Now click on the title link. to redirect the dynamic page.

dynamicpage

show record dynamically

Figure4

Conclusion:

The URL Rewriting is very useful for working with community website. If there is any mistake in this article then please notify me. I expect your valuable comments and feedback about this article.