Home ProgrammingASP.NET URL Re-write using Global.asax in ASP.NET

URL Re-write using Global.asax in ASP.NET

by John Bhatt
2326 views

Hi,

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.

URL Re-write using Global.asax

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.

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("DefaultWebsite", "{PageName}", "~/Default.aspx");

        rColl.MapPageRoute("DefaultDownloads", "Song/{SongID}/{SongURL}.aspx", "~/SongDetails.aspx");

        rColl.MapPageRoute("DefaultNews", "{Category}/{NewsID}/{NewsURL}.aspx", "~/NewsDetails.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.
If you want to see live working demo of above code, we have Shared Hosting that is fully customized which is hosting [button color=”green” size=”small” link=”http://media.johnbhatt.com” icon=”” target=”true”]Download Center[/button]. You can click on any of song there and you can see dynamic URL which seems SEO friendly.

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

Lets move to the file which will handle the request.

Query on ASPX 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");
        }
    }

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.

rColl.MapPageRoute("DefaultDownloads", "Song/{SongID}/{SongURL}.aspx", "~/SongDetails.aspx");

 

GetDataFromURL() : This function will perform the all query from database and browser address bar.

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

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.

URL Re-write using Global.asax

URL Re-write using Global.asax

You may also like

URL Re-write using Global.asax in ASP.NET

by John Bhatt time to read: 3 min
0