An Example of URL Rewriting With ASP.Net

Introduction

URL rewriting is the process of intercepting an incoming Web request and redirecting the request to a different resource. When performing URL rewriting, typically the URL being requested is checked and, based on its value, the request is redirected to a different URL. For example, a website restructuring web pages of a specified directory or article and when accessing a web page from an article or directory by URL then the URL is automatically moved on to the Blog directory. That happens by URL rewriting.

This article introduces URL rewriting using a data-driven application. This application creates various blogs and these blogs are accessed by the title of the blog.

Database Design for Application

First of all we create a table Blog that has blog information like title, content and so on. This table has a primary key id and a Visit field for the total number visits for a specific blog.

  1. CREATE TABLE Blog  
  2. (  
  3. Id int Identity(1,1) Primary Key,  
  4. Title nvarchar(100),  
  5. Content nvarchar(max),  
  6. Visit int default 0,  
  7. createDate datetime default getDate()  
  8. )  

After designing the table we create two Stored Procedures, one for inserting a blog and another for counting the blog visitors. First we create the "proc_BlogInsert" Stored Procedure to insert a new record or blog entry in the blog table.

  1. CREATE PROCEDURE proc_BlogInsert  
  2. @title nvarchar(100),  
  3. @content nvarchar(max)   
  4. AS  
  5. BEGIN  
  6. if not exists(SELECT Id from Blog Where Title = @title)  
  7. begin  
  8.     INSERT INTO Blog (Title,Content) VALUES (@title,@content)  
  9. end  
  10. END  
Now we create another Stored Procedure, "proc_VisitorIncrement", to increment the visitor counter when a blog is visited.
  1. CREATE procedure proc_VisitorIncrement  
  2. (  
  3. @id int  
  4. )  
  5. AS  
  6. begin  
  7. update Blog set Visit += 1 where Id = @id  
  8. end   

Create Business object and Data Access Layer

We create a Blog class that has properties and a constructor for a blog and it will be used to pass blog data on the UI.

  1. namespace URLRewrittingExample.Blogs  
  2. {  
  3.     public class Blog  
  4.     {  
  5.         private int mId=0;  
  6.         private string mTitle = string.Empty;  
  7.         private string mContent = string.Empty;  
  8.         private int mVisit = 0;  
  9.         public Blog(string title, string content)  
  10.         {  
  11.             mTitle = title;  
  12.             mContent = content;  
  13.         }  
  14.         public Blog(int id, string title, int visit)  
  15.         {  
  16.             mId = id;  
  17.             mTitle = title;  
  18.             mVisit = visit;  
  19.         }  
  20.         public Blog(int id, string title, int visit, string content)  
  21.         {  
  22.             mId = id;  
  23.             mTitle = title;  
  24.             mVisit = visit;  
  25.             mContent = content;  
  26.         }  
  27.         public int Id  
  28.         {  
  29.             get { return mId; }  
  30.             set { mId = value; }  
  31.         }  
  32.         public string Title  
  33.         {  
  34.             get { return mTitle; }  
  35.         }  
  36.         public string Content  
  37.         {  
  38.             get { return mContent; }  
  39.         }  
  40.         public int Visit  
  41.         {  
  42.             get { return mVisit; }  
  43.             set { mVisit = value; }  
  44.         }  
  45.     }  
  46. } 

We need a connection with the database to perform create, insert, update and delete operations on the blog table so we define a connection string in the web.config file.

  1. <connectionStrings>  
  2.     <add name="DbConnectionString" connectionString="Data Source=sandeepss-PC;Initial Catalog=CodeFirst;User ID=sa; Password=123456" providerName="System.Data.SqlClient" />  
  3. </connectionStrings>
After that we create a data access layer. In this layer we have a class BlogDAL (BlogDAL.cs) that has all database related operations for a blog in the application.

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.SqlClient;  
  4. using System.Configuration;  
  5. using System.Data;  
  6. namespace URLRewrittingExample.Blogs  
  7. {  
  8.     public class BlogDAL  
  9.     {  
  10.         public static SqlConnection DatabaseConnection()  
  11.         {  
  12.             string connectionString = ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString;  
  13.             SqlConnection con = new SqlConnection(connectionString);  
  14.             if (con.State == ConnectionState.Closed)  
  15.             {  
  16.                 con.Open();  
  17.             }  
  18.             return con;  
  19.         }  
  20.         public int BlogInsert(Blog objBlog)  
  21.         {  
  22.             using (SqlCommand cmd = new SqlCommand("proc_BlogInsert", DatabaseConnection()))  
  23.             {  
  24.                 using (SqlDataAdapter dap = new SqlDataAdapter(cmd))  
  25.                 {  
  26.                     dap.InsertCommand = cmd;  
  27.                     dap.InsertCommand.CommandType = CommandType.StoredProcedure;  
  28.                     dap.InsertCommand.Parameters.AddWithValue("@title", objBlog.Title);  
  29.                    dap.InsertCommand.Parameters.AddWithValue("@content", objBlog.Content);  
  30.                     return dap.InsertCommand.ExecuteNonQuery();  
  31.                 }  
  32.             }  
  33.         }  
  34.         public List<Blog> GetAllBlogs()  
  35.         {  
  36.             List<Blog> blogsList = new List<Blog>();             
  37.             SqlCommand cmd = new SqlCommand("Select Id,Title,Visit from Blog", DatabaseConnection());  
  38.             IDataReader dr = cmd.ExecuteReader();  
  39.             while (dr.Read())  
  40.             {  
  41.                 blogsList.Add(new Blog(Convert.ToInt32(dr["Id"].ToString()),dr["Title"].ToString(),  
  42.                                             Convert.ToInt32(dr["Visit"].ToString())));  
  43.             }  
  44.             dr.Close();  
  45.             return blogsList;  
  46.         }  
  47.         public Blog GetBlogById(int id)  
  48.         {  
  49.             Blog objBlog = null;  
  50.             SqlCommand cmd = new SqlCommand("Select Title,Visit,Content from Blog where Id="+id, DatabaseConnection());  
  51.             IDataReader dr = cmd.ExecuteReader();  
  52.             while(dr.Read())  
  53.             {  
  54.              objBlog = new Blog(id,  
  55.                                 dr["Title"].ToString(),  
  56.                                 Convert.ToInt32(dr["Visit"].ToString()),  
  57.                                 dr["Content"].ToString());  
  58.             }  
  59.             dr.Close();  
  60.             return objBlog;  
  61.         }  
  62.         public int BlogVisitorIncrement(int id)  
  63.         {  
  64.             using (SqlCommand cmd = new SqlCommand("proc_VisitorIncrement", DatabaseConnection()))  
  65.             {  
  66.                 cmd.CommandType = CommandType.StoredProcedure;  
  67.                 using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))  
  68.                 {  
  69.                     adapter.UpdateCommand = cmd;                     
  70.                     SqlParameter param = new SqlParameter("@id",id);  
  71.                     adapter.UpdateCommand.Parameters.Add(param);  
  72.                     return adapter.UpdateCommand.ExecuteNonQuery();  
  73.                 }  
  74.             }  
  75.         }  
  76.     }  
  77. }

Our business object and data access layer is ready.

Application UI Design

We create a UI design for the application. This application has a three-part UI.

  1. Insert a Blog

  2. Show All Blog List

  3. Show individual Blog with Content

Let's see each one by one.

Insert a Blog

To insert a blog we design a UI page that can take two inputs, one is the blog title and the other is blog content. For the blog title we use a TextBox and for the blog content we use an Editor of AjaxControlToolkit. We also use a submit button on the page that inserts a blog record.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="AnExampleOfURLRewriting.Index" %>  
  2. <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit.HTMLEditor" TagPrefix="cc1" %>  
  3. <!DOCTYPE html>  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.     <title></title>  
  7.     <link href="Style/BaseStyleSheet.css" rel="stylesheet" />  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.       <asp:ScriptManager ID="ScriptManager1" runat="server">  
  12.         </asp:ScriptManager>  
  13.     <div class="formRowContainer">  
  14.         <div class="labelContainer">Title</div>  
  15.         <div class="valueContainer">  
  16.             <asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>  
  17.         </div>  
  18.     </div>  
  19.     <div class="clearStyle"></div>  
  20.     <div class="formRowContainer">  
  21.         <div class="labelContainer">Content</div>  
  22.         <div class="valueContainer">  
  23.             <cc1:Editor id="blogEditor" runat="server"></cc1:Editor>             
  24.         </div>  
  25.     </div>  
  26.     <div class="clearStyle"></div>  
  27.         <div class="buttonContainer">  
  28.             <asp:Button ID="btnSubmit" runat="server" Text="Create" OnClick="btnSubmit_Click" />  
  29.         </div>  
  30.     </form>  
  31. </body>  
  32. </html>

After designing the UI, we write the logic on its code behind file for inserting a blog. There is a submit button click event that insert a record in the database.

  1. using System;  
  2. using URLRewrittingExample.Blogs;  
  3. namespace AnExampleOfURLRewriting  
  4. {  
  5.     public partial class Index : System.Web.UI.Page  
  6.     {  
  7.         protected void Page_Load(object sender, EventArgs e)  
  8.         {  
  9.         }  
  10.         protected void btnSubmit_Click(object sender, EventArgs e)  
  11.         {  
  12.             Blog objBlog = new Blog(txtTitle.Text.Trim(), blogEditor.Content);  
  13.             BlogDAL objBlogDAL = new BlogDAL();  
  14.             int effectedRows = objBlogDAL.BlogInsert(objBlog);  
  15.         }  
  16.     }  
  17. }

UrlRewriting1.jpg

Figure 1.1 : UI screen for new blog insert

Show All Blog List

We create a UI screen that shows all blog titles along with total visitor counter. To create a blog list we use a repeater control of ASP.Net. In a repeater we use a link button for the title so we can click on the title and get blog data on the new page.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="BlogList.aspx.cs" Inherits="URLRewrittingExample.Blogs.BlogList" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6.     <link href="../Style/BaseStyleSheet.css" rel="stylesheet" />  
  7. </head>  
  8. <body>  
  9.     <form id="form1" runat="server">  
  10.     <div>  
  11.         <asp:Repeater ID="rptBlog" runat="server" OnItemDataBound="rptBlog_ItemDataBound">  
  12.             <HeaderTemplate>  
  13.                 <table class="gridtable">  
  14.                 <tr>  
  15.                     <th>Title</th>  
  16.                     <th>Visit</th>  
  17.                 </tr>  
  18.             </HeaderTemplate>  
  19.             <ItemTemplate>  
  20.                 <tr>  
  21.                     <td><asp:LinkButton id="lnkTitle" runat="server" Text='<%#Eval("Title") %>'></asp:LinkButton></td>  
  22.                     <td><%#Eval("Visit") %></td>  
  23.                 </tr>  
  24.             </ItemTemplate>  
  25.             <FooterTemplate>  
  26.                 </table>  
  27.             </FooterTemplate>  
  28.         </asp:Repeater>  
  29.     </div>  
  30.     </form>  
  31. </body>  
  32. </html>

Now create a method in the code behind file for a repeater bind and create a custom URL according to the title of the blog.

  1. using System;  
  2. using System.Web.UI;  
  3. using System.Web.UI.WebControls;  
  4. namespace URLRewrittingExample.Blogs  
  5. {  
  6.     public partial class BlogList : System.Web.UI.Page  
  7.     {  
  8.         protected void Page_Load(object sender, EventArgs e)  
  9.         {  
  10.             if (!Page.IsPostBack)  
  11.             {  
  12.                 ShowBlogList();  
  13.             }  
  14.         }  
  15.         private void ShowBlogList()  
  16.         {  
  17.             BlogDAL objBlogDAL = new BlogDAL();  
  18.             rptBlog.DataSource = objBlogDAL.GetAllBlogs();  
  19.             rptBlog.DataBind();  
  20.         }  
  21.         protected void rptBlog_ItemDataBound(object sender, RepeaterItemEventArgs e)  
  22.         {  
  23.             if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)  
  24.             {  
  25.                 LinkButton lnkTitle = (LinkButton) e.Item.FindControl("lnkTitle");  
  26.                 lnkTitle.Style.Add("text-decoration""none");  
  27.                 Blog Item =(Blog) e.Item.DataItem;  
  28.                 lnkTitle.PostBackUrl = GenerateURL(Item.Title, Item.Id);  
  29.             }  
  30.         }  
  31.         public static string GenerateURL(string title, int Id)  
  32.         {  
  33.             string strTitle = title.Trim();  
  34.             strTitle = strTitle.ToLower();            
  35.             strTitle = strTitle.Replace("c#""C-Sharp");  
  36.             strTitle = strTitle.Replace(" ""-");  
  37.             strTitle = strTitle.Trim();            
  38.             strTitle = strTitle.Trim('-');  
  39.             strTitle = "~/Blogs/"+strTitle+"-"+Id.ToString() + ".aspx";  
  40.             return strTitle;  
  41.         }  
  42.     }  
  43. }

UrlRewriting2.jpg

Figure 1.2 : Show all blog list

Show individual Blog with Content

Now create a simple page with a div to show blog content along with blog title and visitor number.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="BlogShow.aspx.cs" Inherits="URLRewrittingExample.Blogs.BlogShow" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.     <div>  
  10.     <div id="divTitle" runat="server"></div>  
  11.         <span id="spVisitor" runat="server"></span>  
  12.     <div id="divContent" runat="server"></div>  
  13.     </div>  
  14.     </form>  
  15. </body>  
  16. </html>

After that we write logic for the code behind page for two operations, one is the show content page and the other is for the visitor counter. The visitor counter increments when the page is initialized.

  1. using System;  
  2. namespace URLRewrittingExample.Blogs  
  3. {  
  4.     public partial class BlogShow : System.Web.UI.Page  
  5.     {  
  6.         protected void Page_Init(object sender, EventArgs e)  
  7.         {  
  8.             if (Request.QueryString.Get("id") != null)  
  9.             {  
  10.                 int id= Convert.ToInt32(Request.QueryString.Get("id"));  
  11.                 BlogDAL objBlogDAL = new BlogDAL();  
  12.                 objBlogDAL.BlogVisitorIncrement(id);  
  13.             }  
  14.         }  
  15.         protected void Page_Load(object sender, EventArgs e)  
  16.         {  
  17.             if (Request.QueryString.Get("id") != null)  
  18.             {  
  19.                 int id = Convert.ToInt32(Request.QueryString.Get("id"));  
  20.                 DisplayBlog(id);  
  21.             }  
  22.         }  
  23.         private void DisplayBlog(int id)  
  24.         {  
  25.             BlogDAL objBlogDAL = new BlogDAL();  
  26.             Blog objBlog = objBlogDAL.GetBlogById(id);  
  27.             divTitle.InnerHtml = objBlog.Title;  
  28.             spVisitor.InnerHtml ="<b>Total Visits "+ objBlog.Visit;  
  29.             divContent.InnerHtml = objBlog.Content;  
  30.         }  
  31.     }  
  32. }

UrlRewriting3.jpg

Figure 1.3 Blog content with different URL

In Figure 1.3 you have noticed a different SEO friendly URL for a .aspx page. That page doesn't exist in our blog application but it is created by URL rewriting. URL rewriting implements the global.asax file's Application_BeginRequest event. This event calls every request and maps the URL on based on the requested URL.

  1. protected void Application_BeginRequest(object sender, EventArgs e)  
  2. {  
  3.     string origionalpath = Request.Url.ToString();  
  4.     string subPath = string.Empty;  
  5.     string blogId = string.Empty;  
  6.     int id = 0;  
  7.     if (origionalpath.Contains("Blogs"))  
  8.     {  
  9.         if (origionalpath.Length >= 22)  
  10.         {  
  11.             subPath = origionalpath.Substring(22);  
  12.             if (subPath.Length >= 1)  
  13.             {  
  14.                 blogId = Regex.Match(subPath, @"\d+").Value;  
  15.                 bool isValid = Int32.TryParse(blogId, out id);  
  16.                 if (isValid)  
  17.                 {  
  18.                     Context.RewritePath("BlogShow.aspx?id=" + id);  
  19.                 }  
  20.             }  
  21.         }  
  22.     }  
  23. }

Note: Download the zip folder that has all files for this application and learn URL rewriting with ASP.NET using 3-tier architecture.


Similar Articles