Click here to Skip to main content
15,885,944 members
Articles / Web Development / ASP.NET
Tip/Trick

URL Re-Writing with Global.asax

Rate me:
Please Sign up or sign in to vote.
4.75/5 (6 votes)
4 Oct 2015CPOL3 min read 18.6K   10   2
We will learn how to achieve URL Re-Writing using Global.asax file in ASP.NET to created SEO friendly URLs in our website or blog created with ASP.NET.

Introduction

Let's come back to the ASP.NET series again. We have had 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

Let's start with simple steps. We will show you an example of our CMS project that is under construction. However, we will try to cover the basic steps from beginning to end to get the 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.

Now, open the newly added Global.asax file and import a namespace called Web.Routing. Let's take a look at the code.

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

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

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

C#
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 a live working demo of the above code, we have Shared Hosting that is fully customized which is at Download Center.

You can click on any of the songs there and you can see dynamic URL which seems SEO friendly. You can add as much as you want but the 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 starts & Session Ends.

C#
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:

C#
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. Let's have a look at our logic that we have used to re-direct here.

C#
<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 the above code, the code is in a similar format as in Global.asax file. Want to be reminded? Here is the code.

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

GetDataFromURL(): This function will perform 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 is 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.

Let's have a look at the working demo.

Have a look at the URL in the Address bar of the attached screenshot.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder P.Yar.B Complex
Nepal Nepal
John Bhatt is an IT Professional having interest in Web technology. He is Web Designer, Developer, Software Developer, Blogger and Technology Geek. Currently he writes his Blogs at Blog of P.Yar.B and various other Sites. He is Main author and founder of Download Center.
Contact Him at : Facebook | Twitter | Website | PRB - Blog.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Camilo Reyes6-Oct-15 3:50
professionalCamilo Reyes6-Oct-15 3:50 
GeneralRe: My vote of 5 Pin
John Bhatt6-Oct-15 3:57
professionalJohn Bhatt6-Oct-15 3:57 
Thanks for reading.
----------
John Bhatt

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.