Sometimes we need a user friendly URL, but if we use query string variables, our site url will become messy.

Like we may be having

URL A: http://www.asphostportal.com/product.aspx?id=123456

and we want to have a URL for above as

URL B: http://www.asphostportal.com/product_123456.aspx

Obviously from above two the 2nd one is more user friendly and easily readable. Now the question is how to accomplish this task. The solution is very simple. In following I will be explaining the solution in detail

About ASPHostPortal.com

ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for more information

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 in VB and C# programming language. You can modify this code as per your need.

VB

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