Home ProgrammingASP.NET Rewriting URL in ASP.NET C# in 2 steps for better search listing

Rewriting URL in ASP.NET C# in 2 steps for better search listing

by John Bhatt
2502 views

Lets come back to ASP.NET series again, We have few more articles on ASP.NET before. This article is about making your website more SEO friendly. In the same topic, we have published a step by step tutorial on how to get dynamic meta tags and description from DataBase.

Rewriting URL in ASP.NET c#

Lets start with simple steps, We will show you example of our CMS project that is under construction. However, we will try to cover the basic steps from beginning to final to get job done with screenshots.

Global.asax

As you add new item in your project in visual studio, you see a file type called Global Application Class.

Rewriting URL in ASP.NET c# / Adding Global.asax
Adding Global.asax

Now open the newly added Global.asax file and import a namespace called Web.Routing. Lets have look at code.

<%@ Application Language="C#" %>

<%@ Import Namespace="System.Web.Routing" %>

Now create a function with any convenient names with below details. I have created function with RegisterRoutes

 public static void RegisterRoutes(RouteCollection rColl)
    {
        rColl.MapPageRoute("DefaultDownloads", "Song/{SongID}/{SongURL}.aspx", "~/SongDetails.aspx");
    }

Let’s discuss the code above:

DefaultDownloads is just the name.
Song/{SongID}/{SongURL}.aspx Song is just text and {SongName} & {SongURL} are two variables which we will replace with value in Browser’s Address bar and use for searching in database.
~/SongDetails.aspx is page which will do the query display data in users page according to PageRoutes.

In the CMS we are developing, we have currently three modules ready, so we have three RouteCollections named one for website, one for Downloads and one for news.

You can add as much as you want but work is not done yet. We still have to do something in Global.asax file.

We have to set the above function execute on Application start event. Global.asax is designed to control the global settings like what to do when Application Starts or Ends or gets error, Session start & Session Ends.

void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup
        RegisterRoutes(RouteTable.Routes);
    }

Now you are all set on part of Global.asax for Rewriting URL in ASP.NET c#.

Lets move to the file which will handle the request.

Query to Load Page Content on ASPX.CS page

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
           GetDataFromURL();
    }

    void GetDataFromURL()
    {
        string SongName = Page.RouteData.Values["SongID"].ToString();
        if (SongName.Length>0)
        {
        int songID = Convert.ToInt16( SongName.Substring(SongID.LastIndexOf('-') + 1));
        GetData(songID);
        }
                else
        {
            Response.Redirect("~/Default.aspx");
        }
    }

Rewriting URL in ASP.NET c# – Adding Link as RouteTable

But remember, to be so we have the Address set to correct location. Lets have look at our logic what we have used to re-direct here.

<a href='<%# String.Format("Song/{0}/{1}.aspx",Eval("SongID"),((string)Eval("SongURL")).Replace(" ", "-"))%>' runat="server">
  <asp:Label ID="lblSongTitle" runat="server" Text='<%#Eval("SongTitle")%>'></asp:Label></a>

Have a look at above code, the code is in similar format as in Global.asax file, want reminded, here is the code.

href='<%# String.Format("Song/{0}/{1}.aspx",Eval("SongID"),((string)Eval("SongURL")).Replace(" ", "-"))%>'
rColl.MapPageRoute("DefaultDownloads", "Song/{SongID}/{SongURL}.aspx", "~/SongDetails.aspx");

Rewriting URL in ASP.NET c# – aspx.cs Steps

Find Current URL on Browser & Check if is has required ID

GetDataFromURL() : This function will perform a query from browser address-bar & checks if it has required ID field.

Extracting ID from URL & Match with Route

Page.RouteData.Values[“SongID”].ToString(); : If you remember, we have put {SongName} in global.asax page earlier. This the the same. We have requested the value of SongName from browser.

Load & Display Data based on ID

GetData(songID): This is the same ID we will use to query and GetData is a function that will load data based on SongID.

Lets have a look at working demo.

Rewriting URL in ASP.NET c#/ URL Re-write using Global.asax
Rewriting URL in ASP.NET c#
Rewriting URL in ASP.NET c# / URL Re-write using Global.asax
Rewriting URL in ASP.NET c#

Well, with few simple steps, you have been able to achieve Rewriting URL in ASP.NET C#. Keep checking for more such technical tutorials.

Reference: System.Web.Routing namespace Microsoft Documentation

Related Articles

Do NOT follow this link or you will be banned from the site!