URL Rewriting in ASP.NET with Sample Project
URL rewriting is the process of intercepting an incoming Web request and automatically redirecting it to a different URL.
To understand completely follow below link
http://msdn.microsoft.com/en-us/library/ms972974.aspx
In this article I am going make a simple example which will take only few minutes and you will learn how to achieve URL Rewriting.
I believe developer doesn’t have much time to read a complete article of 20 pages.
Here we go
Step 1
Create a table
(
POSTID INT,
TITLE VARCHAR(255),
BODY TEXT
)
CREATE TABLE TESTTABLE
Insert some dummy values
INSERT INTO TESTTABLE (POSTID,TITLE,BODY) VALUES (1,‘ACCORDIAN CONTROL WITH SQL SERVER’,
‘ACCORDIAN CONTROL WITH SQL SERVER CONNECTIVITY JOGGEE
MADE A ARTICLE AND THAT IS THE BEST I THINK SO.’)
GO
INSERT INTO TESTTABLE (POSTID,TITLE,BODY) VALUES (2,‘Mouse over effect’,
‘This is so simple and can found thousand places but I tried to make it more easier who
doesnt know the different between <asp:linked button> or anchor.’)
GO
�
SELECT * FROM TESTTABLE
STEP – 2
Create a stored procedure
Create PROCEDURE PROC_TEST
AS
BEGIN
SELECT
‘<A HREF=Detail/’+REPLACE(TITLE,‘ ‘,‘_’) +‘~’ + CONVERT(VARCHAR,POSTID) + ‘.ASPX>’ + TITLE + ‘</A>’ AS ‘TITLE’,
BODY
FROM TESTTABLE
END
GO
Procedure for Detail Page.
CREATE PROCEDURE PROC_TESTDETAIL
@ID INT
AS
BEGIN
SELECT
POSTID,
TITLE,
BODY
FROM TESTTABLE
WHERE POSTID = @ID
END
GO
Database work is finished, let move to ASP.NET project means Website Programming.
Create a Website, Ajax Enabled or not its up to you, No matter what you choose.
In a default webpage write below code. I am pasting the complete code for Default page. where i am using DataList direct binding with two field.
<@ Page Language=”VB” AutoEventWireup=”true” CodeFile=”Default.aspx.vb” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>BLOG.JOGGEE</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” />
<div>
<asp:DataList ID=”DataList1″ runat=”server”>
<ItemTemplate>
<table width=”100%”>
<tr>
<td><%# Container.DataItem(“Title”)%></td>
</tr>
<tr>
<td><%#Container.DataItem(“Body”)%></td>
</tr>
</table>
</ItemTemplate>
</asp:DataList></div>
</form>
</body>
</html>
In a Code Behind Past below code.
Imports System.Data.SqlClientPartial Class _Default
Inherits System.Web.UI.PageProtected
If IsPostBack = False Then
Dim sqlConn As New SqlConnection
Dim sqlCmd As New SqlCommand(“PROC_TEST”, sqlConn)
Dim objDA As New SqlDataAdapter
Dim DT As New DataTable
‘******************************************************************************************************
‘I have mentioned this connection string in the web.config Change it with appropriate values.
‘<add name=”connString” connectionString=”Data Source=”DATABASE SERVER NAME”;Initial Catalog=”DATABASE NAME”;User=”USER”;Password=”PASWORD”;”/>
‘****************************************************************************************************************
sqlConn.ConnectionString = ConfigurationManager.ConnectionStrings(“connString”).ConnectionString
‘opening a connection
sqlConn.Open()
sqlCmd.Connection = sqlConn
sqlCmd.CommandType = CommandType.StoredProcedure
objDA.SelectCommand = sqlCmd
‘populate data table
objDA.Fill(DT)
‘bind data
DataList1.DataSource = DT.DefaultView
DataList1.DataBind()
‘disposing all the declared objects.
objDA.Dispose()
objDA = Nothing
sqlConn.Close()
sqlConn = Nothing
sqlCmd.Dispose()
sqlCmd.Connection.Close()
sqlCmd = Nothing
End If
End Sub
End Class
Code for Detail WebPage.
Create a folder named “Detail” and add one more Default.aspx webpage. Please follow the instructions.
<% @ Page Language=”VB” AutoEventWireup=”false” CodeFile=”Default.aspx.vb” Inherits=”Detail_Default” %>
<! DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>Blog.Joggee</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:HyperLink ID=”HyperLink1″ runat=”server” NavigateUrl=”~/Default.aspx”>Back</asp:HyperLink>
<table width=”100%”>
<tr>
<td>
Title
</td>
<td>
<asp:Label ID=”lblTitle” runat=”server”></asp:Label>
</td>
</tr>
<tr>
<td style=”height: 191px” valign=”top”>
Body:
</td>
<td style=”height: 191px”>
<asp:TextBox ID=”txtBody” runat=”server” Height=”188px” TextMode=”MultiLine” Width=”975px”></asp:TextBox>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
In a Code Behind Just Copy Paste
Imports System.Data
Imports System.Data.SqlClient
Partial Class Detail_Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim sqlConn As New SqlConnection
Dim sqlCmd As New SqlCommand(“PROC_TESTDETAIL” , sqlConn)
Dim objDA As New SqlDataAdapter
Dim DT As New DataTable
‘Here you can specify your connection string.
sqlConn.ConnectionString = ConfigurationManager.ConnectionStrings(
“connString” ).ConnectionString
‘opening a connection
sqlConn.Open()
sqlCmd.Connection = sqlConnsqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.Parameters.Add(“@ID”, SqlDbType.Int).Value = Request.QueryString(“ID” )
objDA.SelectCommand = sqlCmd
‘populate data table
objDA.Fill(DT)
‘bind data
lblTitle.Text = DT.Rows(0)(“Title” )
txtBody.Text = DT.Rows(0)(“Body” )
‘disposing all the declared objects.
objDA.Dispose()
objDA =Nothing
sqlConn.Close()
sqlConn =Nothing
sqlCmd.Dispose()
sqlCmd.Connection.Close()
sqlCmd =Nothing
End If
End Sub
End Class
Add Global.asax file in the project on the root
<%@ Application Language=”VB” %>
<script runat=”server”>
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
‘ Code that runs on application startup
End Sub
Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
‘ Code that runs on application shutdown
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
‘ Code that runs when an unhandled error occurs
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
‘ Code that runs when a new session is started
End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
‘ Code that runs when a session ends.
‘ Note: The Session_End event is raised only when the
‘ sessionstate mode
‘ is set to InProc in the Web.config file. If session
‘mode is set to StateServer�
‘ or SQLServer, the event is not raised.
End Sub
Protected Sub Application_BeginRequest(ByVal sender As Object, ByVal e As System.EventArgs)
Dim Old As String
Dim MovingPath As String
Dim IncomingURL As HttpContext
Dim StartingIndex As Integer
Dim ID As String
IncomingURL = HttpContext.Current
Old = IncomingURL.Request.Path
‘here you can filtered with if condition if you don’t
want any directory to be caught and redirected some where
If Regex.IsMatch(Old, “/Detail/”) Then
Old = Old.Replace(“.ASPX”, “”)
StartingIndex = Old.IndexOf(“~”)
ID = Old.Remove(0, StartingIndex + 1)
MovingPath = “~/Detail/Default.aspx?id=” + ID.ToString
IncomingURL.RewritePath(MovingPath)
End If
End Sub
</script>
In a web.config Add this key
<add name=“connString“ connectionString=“Data Source=“DATABASE SERVER NAME“;Initial Catalog=“DATABASE NAME“;User=“USER“;Password=“PASWORD“;“/>
</connectionStrings>
CLICK HERE TO DOWNLOAD THE COMPLETE SAMPLE PROJECT
Joggee







Its great Artical to understand the URL Rewriting in ASP.Net
Thanks
This was really helpful! Short and sweet and to the point. Thank You!
Its a Informative Article, helpful one…. Thanks.
DotNetGuts
http://dotnetguts.blogspot.com
Thank you in advanced!
Still way too much overkill for the basics of URL rewriting.
For an example, just put some test links on a page and not worry about fussing w/a database, datalists, templates and other completely unrelated stuff.
Keep the regex stuff, though, for sites with articles or products, etc., that is a must.
Thanks, good example of URL Rewriting…..
no c# file?
Wow nice information you have here.thanks for sharing
hello there,
im new programmer, im tryin to make url rewriter at my website , and its look the example that i need…
can u help me with c# example for that code?
plz, i really need help with that:)
have a good day.
@traslochi milano: A c# approach to url rewriting is discussed here – http://runtingsproper.blogspot.com/2009/11/advanced-url-rewriting-for-rest-of-us.html