The Problem:
At number of occasions we need a user friendly URL instead of a messy URL having the query string variables.
Like we may be having
URL A: http://www.mywebpage.com/product.aspx?id=123476576
and we want to have a URL for above as
URL B: http://www.mywebpage.com/product_123476576.aspx
Obviously from above two the 2nd one is more user friendly and easily readable. Now the question is how to accomplish this task. Okay solution is not at all a complex solution. In following I will be explaining the solution in detail
The Solution
Though there are more than one ways for this task but I will make use of the method "application_beginrequest" of "Global.asax". This method is called every time some request is made to the website.
Following will be the code to convert URL A into URL B. You can modify this code as per your need.
Public Sub application_beginrequest(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim initialurl As String = Request.Url.ToString
If initialurl.ToLower.IndexOf("product_") >= 0 Then
Dim mTemp As String = initialurl.Substring(initialurl.LastIndexOf("_") + 1)
Dim mProductID As Integer = mTemp.Substring(0, mTemp.LastIndexOf(".aspx"))
Dim mOriginalURL As String = "product.aspx?id=" + mProductID
Context.RewritePath(mOriginalURL)
End If
'Code to Log your Error
Catch ex As Exception
End Try
End Sub
CSharp (C#)
public void application_beginrequest(object sender, EventArgs e)
{
try
{
string initialurl = Request.Url.ToString();
if (initialurl.ToLower().IndexOf("product_") >= 0)
{
string mTemp = initialurl.Substring(initialurl.LastIndexOf("_") + 1);
int mProductID = Convert.ToInt32(mTemp.Substring(0, mTemp.LastIndexOf(".aspx")));
string mOriginalURL = "product.aspx?id=" + mProductID;
Context.RewritePath(mOriginalURL);
}
}
catch (Exception ex)
{
//Code to Log your Error
}
}
No comments:
Post a Comment